<?php
$MODULE="PMSI";
$TITLE="Traitement des données RSS/RSF";
$DFTENDSTATUS="OK";
$ARGS="";
/** Laisser les lignes 2 à 5 sans changer la casse et sans espaces et dans cet ordre
 * car le script est lu et analysé quand il est exécuté via .exe ou Jenkins
 * pour gestion des fichiers .pid dans system\batch\logs
 */

if (!defined('__ROOT__') ) {
    list($environmentPath) = explode(DIRECTORY_SEPARATOR.'modules', dirname(__FILE__));
    $environmentPath .= DIRECTORY_SEPARATOR;
    define('__ROOT__', $environmentPath);
}

require_once __ROOT__ . '/modules/base/php/lib/cti/bootstrapApp.php';

require_once __ROOT__ . '/modules/base/php/lib/cti/Batch/iCTI_batch_common.php';
require_once __ROOT__ . '/modules/base/php/classSimpleXML.php';
require_once __ROOT__ . '/modules/outils/php/httpService_cacheManager_cleanCache.php';
require_once __ROOT__ . '/modules/pmsi/php/EtudeManager.php';
require_once __ROOT__ . '/modules/base/php/Functions.php';
require_once __ROOT__ . '/modules/base/php/Encoding.php';
require_once __ROOT__ . '/modules/pmsi/import_rss_rsf/utils/import_functions.php';

// Fonctions read_lines
require_once __ROOT__ . '/modules/pmsi/import_rss_rsf/formats/out/read_lines/ano_line.php';

// Fonctions offseets
require_once __ROOT__ . '/modules/pmsi/import_rss_rsf/formats/out/offsets/ano_offset.php';



// Constantes
define("ETABLISSEMENT_PRIVE", "1");
define("ETABLISSEMENT_PUBLIC", "2");
define("ETABLISSEMENT_ESPIC", "3");

global $ENDSTATUS;
global $iCTI_connexion;
global $iCTI_cache;
global $SHS_connexion;

global $trans_sqlcmd_array;
global $nbtrans;

global $ENV_TYPEETS;
global $ENV_FINESS;
global $ENV_PMSIPROVIDER;
global $ENV_PMSIPROVIDER2;
global $ENV_ADMPROVIDER;
global $ENV_LOCALKEYS;
global $ENV_OPTPMSI_GHSBB;
global $ENV_OPTPMSI_FSD_B;
global $ENV_OPTPMSI_MED_CODOUID;
global $ENV_OPTIMISATIONS_VUES_MATERIALISEES;

global $SHS_connected;
global $SHS_admlib;
global $SHS_gefilib;

global $import_id;

global $annee_fin;

global $aspirator_host;


global $med_array;
global $rssmed_array;
global $rssnom_array;
global $rssprenom_array;
global $actmed_array;
global $val_array;

global $file_MED;
global $file_RSSMED;
global $file_RSSNOM;
global $file_ACTMED;

// Fichiers IN
global $file_RSS;
global $file_RSF;
global $file_VSJ;
global $file_VSE;
global $file_FCP;
global $file_TSP;

// Fichiers OUT
global $file_ANO;
global $file_RSA;
global $file_TRA;
global $file_CTL;
global $file_VAL;


global $file_exists_MED;
global $file_exists_RSSMED;
global $file_exists_RSSNOM;
global $file_exists_ACTMED;
global $file_exists_RSS;
global $file_exists_RSF;
global $file_exists_FCP;
global $file_exists_ANO;
global $file_exists_RSA;
global $file_exists_CTL;
global $file_exists_TRA;
global $file_exists_VAL;
global $file_exists_VSJ;
global $file_exists_VSE;
global $file_exists_TSP;

global $rss_offsets_114;
global $rss_offsets_113;
global $rss_offsets_111;
global $rss_offsets_110;
global $rss_offsets_109;

global $rsf_offsets_2006_A;
global $rsf_offsets_2006_B;
global $rsf_offsets_2006_P;
global $rsf_offsets_2006_M;
global $rsf_offsets_2008_A;
global $rsf_offsets_2008_B;
global $rsf_offsets_2008_P;
global $rsf_offsets_2008_M;
global $rsf_offsets_2008B_A;
global $rsf_offsets_2008B_B;
global $rsf_offsets_2008B_P;
global $rsf_offsets_2008B_M;

global $rsf_ace_offsets_2009_A;

global $rsf_ace_offsets_2008_A;
global $rsf_ace_offsets_2008_B;
global $rsf_ace_offsets_2016_B;

global $rsf_ace_offsets_2016_M;
global $rsf_ace_offsets_2008_M;

global $rsf_ace_offsets_2007_A;
global $rsf_ace_offsets_2007_M;

global $fcp_dmi_offsets_2007;
global $fcp_dmi_offsets_2008;
global $fcp_ucd_offsets_2007;
global $fcp_ucd_offsets_2008;

global $current_rsfa_index;

global $omitExpert;         // Omettre le lancement des contrôles expert
global $omitEssentiels;     // Omettre le calcul des essentiels
global $omitComplements;    // Omettre le traitement des données complémentaires

global $versions_groupage;

$omitEssentiels = false;
$omitExpert = false;
$omitComplements = false;

$cti_args = new CTI_Args_class();
foreach ($cti_args->args as $option => $value) {
        switch ($option) {
            case "-xe": // option pour ne pas lancer le calcul des essentiels
                $omitEssentiels = true;
                break;
            case "-xx": // option pour ne pas exécuter les contrôles expert
                $omitExpert = true;
                break;
            case "-xc": // option pour ne pas traiter les données complémentaires
                $omitComplements = true;
                break;
            default :
                break;
        }
}

$versions_groupage = array('09', '1B', '1C', '1D', '1E', '1F', '1G', '10', '11', '12', '13', '14', '16', '17', '18', '19', '20', '21', '22', '23', '79', '89', '99', 'V2');

ini_set('memory_limit','2G');

logStartMsg();

// parametres generaux
$file = "../../../settings/settings.XML";
$settings_xml = simplexml_load_string(file_get_contents($file));

$ENV_CONSOLIDATION = "0";
$ENV_ADMPROVIDER = "";
$ENV_PMSIPROVIDER = "";
$ENV_PMSIPROVIDER2 = "";
$ENV_FINESS = "999999999";
$ENV_LOCALKEYS = "";
$ENV_OPTIMISATIONS_VUES_MATERIALISEES = "";
foreach ($settings_xml->ENVIRONMENT as $environmentNode) {
    foreach ($environmentNode->PROPERTY as $propertyNode) {
        if ($propertyNode['name'] == 'CONSOLIDATION') {
            $ENV_CONSOLIDATION = trim($propertyNode['value']);
        }
        if ($propertyNode['name'] == 'TYPEETS') {
            $ENV_TYPEETS = trim($propertyNode['value']);
        }
        if ($propertyNode['name'] == 'PMSIPROVIDER') {
            $ENV_PMSIPROVIDER = strtolower($propertyNode['value']);
        }
        if ($propertyNode['name'] == 'PMSIPROVIDER2') {
            $ENV_PMSIPROVIDER2 =  strtolower($propertyNode['value']);
        }
        if ($propertyNode['name'] == 'ADMPROVIDER') {
            $ENV_ADMPROVIDER = trim($propertyNode['value']);
        }
        if ($propertyNode['name'] == 'FINESS') {
            $ENV_FINESS = trim($propertyNode['value']);
        }
        if ($propertyNode['name'] == 'LOCALKEYS') {
            $ENV_LOCALKEYS = trim($propertyNode['value']);
        }
        if ($propertyNode['name'] == 'OPTPMSI_GHSBB') {
            $ENV_OPTPMSI_GHSBB = trim($propertyNode['value']);
        }
        if ($propertyNode['name'] == 'OPTPMSI_MED_CODOUID') {
            $ENV_OPTPMSI_MED_CODOUID = trim($propertyNode['value']);
        }
        // Option qui permet de traiter les FSD comme des prestations cliniques et non honoraires ('1' cliniques, '0' honoraires)
        if ($propertyNode['name'] == 'OPTPMSI_FSD_B') {
            $ENV_OPTPMSI_FSD_B = trim($propertyNode['value']);
        }
    }
}

if (isset($settings_xml->OPTIMISATIONS)) {
	foreach ($settings_xml->OPTIMISATIONS as $environmentNode) {
		foreach ($environmentNode->PROPERTY as $propertyNode) {
			if ($propertyNode['name'] == 'VUES_MATERIALISEES') {
				$ENV_OPTIMISATIONS_VUES_MATERIALISEES = trim($propertyNode['value']);
			}
		}
	}
}

if ($ENV_CONSOLIDATION == "1") {
    logErrorMsg("Cet environnement est un environnement consolidé");
    logEndMsg();
    return;
}

if ($ENV_TYPEETS != "2" && $ENV_TYPEETS != "3") {
    $ENV_TYPEETS = "1";
}

$aspirator_host = "inactive";

if (isset($settings_xml->ASPIRATOR)) {
    foreach ($settings_xml->ASPIRATOR as $aspiratorNode) {
        foreach ($aspiratorNode->PROPERTY as $propertyNode) {
            $propertyName = trim($propertyNode['name']);
            $propertyValue = trim($propertyNode['value']);

            if ($propertyName == "HOST") {
                $aspirator_host = $propertyValue;
            }
        }
    }
}


// Connexion iCTI
$iCTI_connexion = Database2Factory::getInstance(Environnement::PROVIDER_CTI);

$ret = $iCTI_connexion->connect();

$trans_sqlcmd_array = array();
$trans_sqlcmd_array_index = 0;

//start traitement
traitements();

$iCTI_connexion->close();

logEndMsg();

// Traitement des imports pointés
function traitements() {
    global $iCTI_connexion;
    global $import_id;

    checkImportState();
    
    init_offsets();
    begin_trans();
        
    $controles_array = array();
    $generations_array = array();

    // Contrôles
    $result = $iCTI_connexion->query("SELECT oid FROM pmsi.p_imports WHERE traitement_a_faire = 'C' ");
    $ok = TRUE;
    while ($ok == TRUE) {
        $ok = FALSE;
        $record = pg_fetch_array($result);
        if ($record != FALSE) {
            $ok = TRUE;
            $oid = $record["oid"];
            $controles_array[$oid] = $oid;
        }
    }
    
    $sqlcmd = "UPDATE pmsi.p_imports SET ";
    $sqlcmd = $sqlcmd . "traitement_a_faire = '' ";
    $sqlcmd = $sqlcmd . "WHERE traitement_a_faire = 'C' ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    
    
    // générations
    $result = $iCTI_connexion->query("SELECT oid FROM pmsi.p_imports WHERE traitement_a_faire = 'G' ");
    $ok = TRUE;
    while ($ok == TRUE) {
        $ok = FALSE;
        $record = pg_fetch_array($result);
        if ($record != FALSE) {
            $ok = TRUE;
            $oid = $record["oid"];
            $generations_array[$oid] = $oid;
        }
    }
    
    $sqlcmd = "UPDATE pmsi.p_imports SET ";
    $sqlcmd = $sqlcmd . "traitement_a_faire = '' ";
    $sqlcmd = $sqlcmd . "WHERE traitement_a_faire = 'G' ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );

    
    commit_trans();
    
    foreach ($controles_array as $oid) {
        $import_id = $oid;
        controle();
    }

    foreach ($generations_array as $oid) {
        $import_id = $oid;
        generation();
    }
    
    if (count($generations_array)) {
        generations_fin();
    }
}

function checkImportState(){
    global $iCTI_connexion;
    
    $imports_avec_pb = array();

    // Vérification des flags en BD
    $result = $iCTI_connexion->query("SELECT oid, texte, date_import FROM pmsi.p_imports WHERE etat_en_cours <> '' ");
    $ok = TRUE;
    while ($ok == TRUE) {
        $ok = FALSE;
        $record = pg_fetch_array($result);
        if ($record != FALSE) {
            $ok = TRUE;
            $imports_avec_pb[$record["oid"]] = "L'import n°" . $record["oid"] . " \"" . $record["texte"] . "\" du " . $record["date_import"] . " est marqué comme étant \"en cours\".";
        }
    }

    if (OperatingSystem::isLinux()) {
        //todo: Gérer les jobs différemment
        return;
    }

    // Vérification des fichiers pid batch
    $activeJobsDirPath = "../../../system/batch/activejobs";
    $notFound = true; // PID du programme en cours pas trouvé
    $cpt = 0; // Pour ne pas boucler indéfiniment

     while ($notFound && $cpt < 10) {
        sleep($cpt * 1);
        $cpt++;
        $activeJobPresent = array();
        $activeJobsDir = opendir($activeJobsDirPath) or die('Erreur');
        while ($activeJob = @readdir($activeJobsDir)) {
            if (is_file($activeJobsDirPath . '/' . $activeJob) && $activeJob != '.' && $activeJob != '..') {
                
                $filename = basename(__FILE__, ".php");
                $aj = preg_split('/\r\n|\r|\n/', file_get_contents($activeJobsDirPath . '/' . $activeJob));
                $ajFilename = str_replace("name=", "", $aj[1]);
                $ajPID = str_replace("pid=", "", $aj[0]);

                if ($filename == $ajFilename) {
                    $tmp = csv2array(shell_exec("tasklist /FO CSV /NH /FI \"PID eq $ajPID\" "));
                    if ($tmp[1] == $ajPID) {
                        // Fichier PID avec un process Windows en cours d'exécution
                        $notFound = false;
                        $activeJobPresent[$activeJob] = array(false, realpath($activeJobsDirPath . '/' . $activeJob));
                    } else {
                        // Fichier PID sans un process Windows en cours d'exécution => flaggé à déplacer
                        $activeJobPresent[$activeJob] = array(true, realpath($activeJobsDirPath . '/' . $activeJob));
                    }
                }
            }
        }
        closedir($activeJobsDir);
    }

    if($notFound){
        logInfoMsg("Pas de process Windows trouvé pour cet import.");
    }

    if (count($imports_avec_pb) > 0 && count($activeJobPresent) == 1) {
        // CAS n°1 :
        // Si import signalé en cours mais 1 seul fichier batch correspondant à cet import RSS RSF
        // => annuler le flag "en cours"
        foreach ($imports_avec_pb as $key => $value) {
            $sqlcmd = "
                UPDATE pmsi.p_imports
                SET etat_en_cours = ''
                WHERE oid = $key
                ;
            ";
            $iCTI_connexion->query($sqlcmd);
            logInfoMsg($value . " Rétablissement de l'état.");
        }
    } else if (count($imports_avec_pb) == 0 && count($activeJobPresent) > 1) {
        // CAS n°2 :
        // Si aucun import signalé en cours mais + d'1 fichier batch
        // => deplacer le fichier dans le repertoire "jobs" => NON tant qu'on ne sait pas associer l'import en cours avec le fichier PID
        foreach ($activeJobPresent as $key => $value) {
            if($value[0]){
                if($notFound){
                    logInfoMsg("Fichier $key présent dans \"system/batch/activejobs/\" .");
                }else{
                    rename($value[1], str_replace("activejobs", "jobs", $value[1]));
                    logInfoMsg("Le fichier $key a été déplacé de \"system/batch/activejobs/\" vers \"system/batch/jobs/\" .");
                }
            }
        }
    } else if (count($imports_avec_pb) > 0 && count($activeJobPresent) > 1) {
        // CAS n°3 :
        // Si import signalé ET + d'1 fichier batch
        // => STOP
        foreach ($imports_avec_pb as $key => $value) {
            logInfoMsg($value . " Merci d'attendre la fin de son traitement.");
        }
        sleep(10);
        logEndMsg();
        exit(0);
    }
}

// controle
function controle() {

    global $import_id;
    global $ENV_TYPEETS;


    global $file_exists_RSF;
    global $file_exists_FCP;
    global $file_exists_TSP;
    
    
    logInfoMsg("CONTROLE FICHIERS N° $import_id");
    
    controle_initialisation();
    
    restauration_fichiers();
    
    restauration_donnees_complementaires();//SUPPR

    controle_ium();
    controle_rss_medecin(); // SUPPR
    controle_rss_nom();  // SUPPR
    controle_acte_med();  // SUPPR
    controle_rum();
    
    if ($ENV_TYPEETS == "1") {
        controle_rsf();
    }
    if ($ENV_TYPEETS != "1") {
        if ($file_exists_RSF) {
            controle_rsf();
        }
    }
    //if ($ENV_TYPEETS != "1") {
        controle_rsa();
    //}
    if ($file_exists_FCP == true) {
        controle_fichcomp();
    }
    if ($file_exists_TSP == true) {
        controle_fichsup();
    }
    else {
        logInfoMsg("Pas de controle des fichsup");
    }
    if ($ENV_TYPEETS != "1") {
        controle_ano_vidhosp();
    }
    
    controle_validation();
    
    suppression_fichiers();
    
    
    logInfoMsg("FIN CONTROLE FICHIERS N° $import_id");

}

function controle_initialisation() {

    global $import_id;

    logInfoMsg("INITIALISATION CONTROLE");

    $nbE = 0;

    begin_trans();

    $sqlcmd = "UPDATE pmsi.p_imports SET ";
    $sqlcmd = $sqlcmd . "finess = '', ";
    $sqlcmd = $sqlcmd . "etat_en_cours = 'C', ";
    $sqlcmd = $sqlcmd . "nb_rss = 0, nb_rum = 0, nb_rsf = 0, ";
    $sqlcmd = $sqlcmd . "nb_erreurs = 0, nb_avertissements = 0, ";
    $sqlcmd = $sqlcmd . "date_debut = '2099-12-31', ";
    $sqlcmd = $sqlcmd . "date_fin = '2099-12-31' ";
    $sqlcmd = $sqlcmd . "WHERE oid = $import_id";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    
    $sqlcmd = "DELETE FROM pmsi.p_imports_controles ";
    $sqlcmd = $sqlcmd . "WHERE import_id = $import_id ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    
    commit_trans();
    
    logInfoMsg("FIN INITIALISATION CONTROLE. $nbE erreurs.");
    
}


function controle_validation() {

    global $import_id;


    logInfoMsg("VALIDATION CONTROLE");

    begin_trans();
    
    $sqlcmd = "UPDATE pmsi.p_imports SET ";
    $sqlcmd = $sqlcmd . "etat_en_cours = '' ";
    $sqlcmd = $sqlcmd . "WHERE oid = $import_id ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );

    $sqlcmd = "UPDATE pmsi.p_imports SET ";
    $sqlcmd = $sqlcmd . "etat = 'C' ";
    $sqlcmd = $sqlcmd . "WHERE oid = $import_id AND etat = 'I'";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    
    commit_trans();
   
    logInfoMsg("FIN VALIDATION CONTROLE. $nbE erreurs.");
    
}

function controle_rss_medecin() {

    
    global $iCTI_connexion;

    global $import_id;
    global $file_RSSMED;
    global $file_exists_MED;
    global $file_exists_RSSMED;
    
    global $med_array;
    global $rssmed_array;
    global $rssmed_deja;
    global $ENV_PMSIPROVIDER;
    
    if ($ENV_PMSIPROVIDER != "" && !$file_exists_RSSMED) {
        return;
    }
    

    logInfoMsg("CONTROLE ASSOCIATION RSS MEDECIN");

    $nb = 0;
    $nbI = 0;
    $nbW = 0;
    $nbE = 0;
    
    begin_trans();
    
    
    if ($file_exists_RSSMED) {
    
        $no_ligne = 0;
        $rssmed_array = array();
        
        $handle = @fopen($file_RSSMED, "r");
        if ($handle) {
            while (!feof($handle)) {
                $buffer = fgets($handle, 99999);
                
                $no_ligne++;
                if (trim($buffer) != "" && $no_ligne < 100000000000 ) {
                
                    $nb++;
                    
                    $okrcd = "OK";
                    
                    $BUF_record = read_rssmed_line($buffer);
                    
                    if ($BUF_record["is_comite"] != "1") {

                        if (! controle_check_num($BUF_record["no_rss"],0,FALSE,$erreur,$commentaire)) {
                            $commentaire = "Ligne ignorée";
                            controle_add_error("RSSMED", $no_ligne, "Numéro RSS", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_record["no_rss_offset"], $BUF_record["no_rss_len"]);
                            $okrcd = "KO";
                        }
                        
                        $code_med = "";
                        if ($file_exists_MED) {
                            if ($BUF_record["code_medecin"] != "") {
                                $code_med = @$med_array[$BUF_record["code_medecin"]];
                                if ($code_med == "") {
                                    if (! check_medecin($BUF_record["code_medecin"], $gravite, $erreur, $commentaire)) {
                                        controle_add_error("RSF", $no_ligne, "Code médecin", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_record["code_medecin_offset"], $BUF_record["code_medecin_len"]);
                                    }
                                }
                            }
                            else {
                                $okrcd = "KO";
                            }
                        }
                        
                        if ($okrcd == "OK") {
                            $no_rss = get_numrss($BUF_record["no_rss"]);
                            $rssmed_array[$no_rss] = $BUF_record["code_medecin"];
                        }
                    
                    }

                }
            
            }
            
            fclose($handle);
        
        }
    
    }
    
    else {
        controle_add_error("FILE", 0, "", "", "Fichier des association RSS - Médecin absent", 1, "", $nbI, $nbW, $nbE);
    
    }
    
    $rssmed_deja = "";
    $sqlcmd = "SELECT base.cti_group_concat(no_rss) AS deja FROM pmsi.p_imports_rss_mednom WHERE medecin_rss_id > 0 AND annee_sortie = (SELECT max(annee_sortie) FROM pmsi.p_imports_rss_mednom)";
    $result = $iCTI_connexion->query($sqlcmd);
    $record = pg_fetch_array($result);
    if ($record != FALSE) {
        $rssmed_deja = ", " . trim($record["deja"]) . ",";
    }
    
    
    
    if ($nbE > 0 || $nbW > 0) {
        

        $sqlcmd = "UPDATE pmsi.p_imports SET ";
        $sqlcmd = $sqlcmd . "nb_erreurs = nb_erreurs + $nbE, nb_avertissements = nb_avertissements + $nbW ";
        $sqlcmd = $sqlcmd . "WHERE oid = $import_id";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );

    }
    
    commit_trans();
    
    
    logInfoMsg("FIN CONTROLE ASSOCIATION RSS MEDECIN. $nb lus, $nbI informations, $nbW avertissements, $nbE erreurs graves");

    
}

function controle_rss_nom() {

    
    global $iCTI_connexion;

    global $import_id;

    global $aspirator_host;

    global $file_MED;
    global $file_RSSMED;
    global $file_RSSNOM;

    global $file_exists_RSSNOM;

    global $rssnom_array;
    global $rssprenom_array;
    global $rssnom_deja;
    global $ENV_PMSIPROVIDER;
    
    if ($ENV_PMSIPROVIDER != "" && !$file_exists_RSSNOM) {
        return;
    }

    logInfoMsg("CONTROLE ASSOCIATION RSS NOM");

    $nb = 0;
    $nbI = 0;
    $nbW = 0;
    $nbE = 0;
    
    begin_trans();
    
    if ($file_exists_RSSNOM) {
    
        $no_ligne = 0;
        $rssnom_array = array();
        $rssprenom_array = array();
        
        $handle = @fopen($file_RSSNOM, "r");
        if ($handle) {
            while (!feof($handle)) {
                $buffer = fgets($handle, 99999);
                
                $no_ligne++;
                if (trim($buffer) != "" && $no_ligne < 100000000000 ) {
                
                    $nb++;
                    
                    $BUF_record = read_rssnom_line($buffer);
                    $okrcd = "OK";

                    if (! controle_check_num($BUF_record["no_rss"],0,FALSE,$erreur,$commentaire)) {
                        $commentaire = "Ligne ignorée";
                        controle_add_error("RSSNOM", $no_ligne, "Numéro RSS", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_record["no_rss_offset"], $BUF_record["no_rss_len"]);
                        $okrcd = "KO";
                    }
                    
                    if ($BUF_record["nom"] == "") {
                        //$erreur = "Nom non renseigné";
                        //$commentaire = "Blanc pris par défaut";
                        //controle_add_error("RSSNOM", $no_ligne, "Nom", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE);
                        $okrcd = "KO";
                    }
                    
                    if ($okrcd == "OK") {
                        $no_rss = get_numrss($BUF_record["no_rss"]);
                        $rssnom_array[$no_rss] = $BUF_record["nom"];
                        $rssprenom_array[$no_rss] = $BUF_record["prenom"];
                    }
                    

                }
            
            }
            
            fclose($handle);
        
        }
    
    }
    
    else {
        controle_add_error("FILE", 0, "", "", "Fichier des association RSS - Noms absent", 1, "", $nbI, $nbW, $nbE);
    
    }
    
    $rssnom_deja = "";
    $sqlcmd = "SELECT base.cti_group_concat(no_rss) AS deja FROM pmsi.p_imports_rss_mednom WHERE nom <> '' AND annee_sortie = (SELECT max(annee_sortie) FROM pmsi.p_imports_rss_mednom)";
    $result = $iCTI_connexion->query($sqlcmd);
    $record = pg_fetch_array($result);
    if ($record != FALSE) {
        $rssnom_deja = ", " . trim($record["deja"]) . ",";
    }
    
    if ($nbE > 0 || $nbW > 0) {

        $sqlcmd = "UPDATE pmsi.p_imports SET ";
        $sqlcmd = $sqlcmd . "nb_erreurs = nb_erreurs + $nbE, nb_avertissements = nb_avertissements + $nbW ";
        $sqlcmd = $sqlcmd . "WHERE oid = $import_id";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );

    }
    
    commit_trans();
    
    
    logInfoMsg("FIN CONTROLE ASSOCIATION RSS NOM. $nb lus, $nbI informations, $nbW avertissements, $nbE erreurs graves");

    
}


function controle_acte_med() {

    global $import_id;
    global $file_ACTMED;
    global $file_exists_MED;
    global $file_exists_ACTMED;

    
    
    global $med_array;
    global $actmed_array;
    global $ENV_PMSIPROVIDER;
    

    if ($ENV_PMSIPROVIDER != "" && !$file_exists_ACTMED) {
        return;
    }

    logInfoMsg("CONTROLE ASSOCIATION ACTES EXECUTANTS");

    $nb = 0;
    $nbI = 0;
    $nbW = 0;
    $nbE = 0;
    
    begin_trans();
    

    if ($file_exists_ACTMED) {
    
        $no_ligne = 0;
        $actmed_array = array();
        
        
        $handle = @fopen($file_ACTMED, "r");
        if ($handle) {
            while (!feof($handle)) {
                $buffer = fgets($handle, 99999);
                
                $no_ligne++;
                if (trim($buffer) != "" && $no_ligne < 10000000000000 ) {
                
                    $nb++;
                    $okrcd = "OK";

                    $BUF_record = read_actmed_line($buffer);
                    
                    if ($BUF_record["type_enregistrement"] == "ACTMED") {

                        if (! controle_check_num($BUF_record["no_rss"],0,FALSE,$erreur,$commentaire)) {
                            $commentaire = "Ligne ignorée";
                            controle_add_error("ACTMED", $no_ligne, "Numéro RSS", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_record["no_rss_offset"], $BUF_record["no_rss_len"]);
                            $okrcd = "KO";
                        }
                        
                        if ($file_exists_MED && $okrcd == "OK") {
                            $code_med = isset($med_array[$BUF_record["code_medecin"]]) ? $med_array[$BUF_record["code_medecin"]] : "";
                            if ($code_med != "") {
                                if (! check_medecin($BUF_record["code_medecin"], $gravite, $erreur, $commentaire)) {
                                    if ($gravite == 4) {
                                        $gravite = 1;
                                        $commentaire = "Ligne ignorée";
                                        $okrcd = "KO";
                                    }
                                    controle_add_error("ACTMED", $no_ligne, "Code médecin", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_record["code_medecin_offset"], $BUF_record["code_medecin_len"]);
                                }
                            }
                            else {
                                $okrcd = "KO";
                            }
                        }

                        
                        // Date acte
                        if ($okrcd == "OK") {
                            if (! controle_check_date($BUF_record["date_acte"],$erreur,$commentaire)) {
                                if ($gravite == 4) {
                                    $gravite = 1;
                                    $commentaire = "Ligne ignorée";
                                    $okrcd = "KO";
                                }
                                controle_add_error("ACTMED", $no_ligne, "Date acte", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_record["date_acte_offset"], $BUF_record["date_acte_len"]);
                                $okrcd = "KO";
                            }
                        }
                                                
                        // code CCAM
                        if ($okrcd == "OK") {
                            if (! check_acte($BUF_record["code_acte"], $gravite, $erreur, $commentaire)) {
                                if ($gravite == 4) {
                                    $gravite = 1;
                                    $commentaire = "Ligne ignorée";
                                    $okrcd = "KO";
                                }
                                controle_add_error("ACTMED", $no_ligne, "Code acte CCAM", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_record["code_acte_offset"], $BUF_record["code_acte_len"]);
                            }
                        }
                        
                        // activite
                        if ($okrcd == "OK") {
                            if (! controle_check_num($BUF_record["activite_ccam"],1, FALSE,$erreur,$commentaire)) {
                                $commentaire = "Valeur 1 prise par défaut";
                                $BUF_record["activite_ccam"] = "1";
                                controle_add_error("ACTMED", $no_ligne, "Activité CCAM", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_record["activite_ccam_offset"], $BUF_record["activite_ccam_len"]);
                            }
                        }
                        
                        if ($okrcd == "OK") {
                            $cle = get_numrss($BUF_record["no_rss"]);
                            $cle = $cle . $BUF_record["code_acte"];
                            $cle = $cle . get_date_AAAAMMJJ($BUF_record["date_acte"]);
                            $cle = $cle . $BUF_record["activite_ccam"];
                            $actmed_array[$cle] = $BUF_record["code_medecin"];
                            
                            $cle = get_numrss($BUF_record["no_rss"]);
                            $cle = $cle . $BUF_record["code_acte"];
                            $cle = $cle . "00000000";
                            $cle = $cle . $BUF_record["activite_ccam"];
                            $actmed_array[$cle] = $BUF_record["code_medecin"];
                            
                            // cas particulier actes anesthésie en activite 1
                            if ($BUF_record["activite_ccam"] == "4") {
                                $acte_anesthesie = array("AFLB010", "GELE001", "YYYY003", "YYYY004", "YYYY015", "YYYY020", "YYYY041", "YYYY044", "YYYY108", "YYYY118", "ZZLP008", "ZZLP012", "ZZLP025", "ZZLP030", "ZZLP042", "ZZLP054");
                                
                                if (in_array($BUF_record["code_acte"], $acte_anesthesie)){
                                    $cle = get_numrss($BUF_record["no_rss"]);
                                    $cle = $cle . $BUF_record["code_acte"];
                                    $cle = $cle . get_date_AAAAMMJJ($BUF_record["date_acte"]);
                                    $cle = $cle . "1";
                                    $actmed_array[$cle] = $BUF_record["code_medecin"];
                                    
                                    $cle = get_numrss($BUF_record["no_rss"]);
                                    $cle = $cle . $BUF_record["code_acte"];
                                    $cle = $cle . "00000000";
                                    $cle = $cle . "1";
                                    $actmed_array[$cle] = $BUF_record["code_medecin"];
                                }
                            }
                        }
                    
                    }

                }
            
            }
            
            fclose($handle);
        
        }
    
    }
    
    else {
        controle_add_error("FILE", 0, "", "", "Fichier des association Actes - Médecin absent", 1, "", $nbI, $nbW, $nbE);
    
    }
    
    if ($nbE > 0 || $nbW > 0) {

        $sqlcmd = "UPDATE pmsi.p_imports SET ";
        $sqlcmd = $sqlcmd . "nb_erreurs = nb_erreurs + $nbE, nb_avertissements = nb_avertissements + $nbW ";
        $sqlcmd = $sqlcmd . "WHERE oid = $import_id";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );

    }
    
    commit_trans();
    
    
    logInfoMsg("FIN CONTROLE ASSOCIATION ACTES EXECUTANTS. $nb lus, $nbI informations, $nbW avertissements, $nbE erreurs graves");

    
}


function controle_ium() {

    /*
     *  [Position debut - Position fin]
     *
     *  version 3 _ depuis M03 2013
     *
     *  [00-03] Code UM                             Notation identique à celle du fichier RSS
     *  [04-12] Finess geographique
     *  [13-15] Type autorisation
     *  [16-23] Date d'effet de l'autorisation      JJMMAAAA
     *  [24-26] Nombre de lits                      3 caractères « espace » si pas d'autorisation, sinon au format « 000 » (par exemple pour un chiffre 2, écrire « 002 »)
     *  [27-27] Mode d'hospitalisation              C : Hospitalisation complète | P : Hospitalisation partielle | M : Hospitalisation Mixte
     *
     *
     *  version 2
     *
     *  [00-03] Code UM                             Notation identique à celle du fichier RSS
     *  [04-12] Finess geographique                 Obligatoire à partir de 2012
     *  [13-14] Type autorisation                   2 caractères espace = pas d'autorisation
     *  [15-22] Date d'effet de l'autorisation      JJMMAAAA
     *  [23-25] Nombre de lits                      3 caractères « espace » si pas d'autorisation, sinon au format « 000 » (par exemple pour un chiffre 2, écrire « 002 »)
     *
     *
     *  version 1
     *
     *  [00-03] Code UM                             Notation identique à celle du fichier RSS
     *  [04-05] Type autorisation                   2 caractères « espace » : Pas d'autorisation
     *  [06-13] Date d'effet de l'autorisation      JJMMAAAA
     *  [14-16] Nombre de lits                      3 caractères « espace » si pas d'autorisation, sinon au format « 000 » (par exemple pour un chiffre 2, écrire « 002 »)
     *
     */
    
    global $file_exists_IUM;
    global $file_IUM;
    global $iCTI_connexion;
    global $import_id;
    
    if (!$file_exists_IUM || !is_readable($file_IUM)) {
        logInfoMsg("FICHIER DES UNITES MEDICALES ABSENT OU ILLISIBLE");
        return;
    }
    else {
        logInfoMsg("CONTROLE DES UNITES MEDICALES");
    }
    
    $no_ligne = 0;
    $nbI = 0;
    $nbW = 0;
    $nbE = 0;
    $autStart = 0;
    $autLength = 0;
    $dateStart = 0;
    
    // Détermine la version du fichiers des IUM en fonction de la longueur max des lignes d'enregistrement
    $f = file_get_contents($file_IUM);
    $a = explode(PHP_EOL, $f);
    $max = 0;
    foreach($a as $line) {
        if (strlen($line) > $max) { $max = strlen($line);}
    }
    if ($max >= 28) {
        $version = 3;
    }
    else if ($max >= 26) {
        $version = 2;
    }
    else {
        $version = 1;
    }
    
    $handle = fopen($file_IUM, "r");
    if ($handle) {
        
        // Récupère les données présentes en base pour les unités médicales, les types d'autorisation et les modes d'hospitalisation
        $modes_hospitalisation = get_modes_hospitalisation();
        $unites_medicales = get_unites_medicales();
        $types_autorisation = get_types_autorisation();
        
        while (!feof($handle)) {
            
            $buffer = fgets($handle);
            
            $no_ligne++;
            
            if (trim($buffer) != "" && $no_ligne < 10000000000000 ) {
            
                switch ($version) {
                    case  3 :
                        
                        $autStart    = 13;
                        $autLength   = 3;
                        $dateStart   = 16;
                        
                        $umCode      = trim(substr($buffer, 0, 4));
                        $umFiness    = trim(substr($buffer, 4, 9));
                        $umAut       = trim(substr($buffer, $autStart, $autLength));
                        $umDate      = trim(substr($buffer, $dateStart, 8));
                        $umNbLits    = trim(substr($buffer, 24, 3));
                        $umMode      = trim(substr($buffer, 27, 1));
                        
                        if (in_array($umMode, $modes_hospitalisation) === false) {
                            
                            $erreur = " Mode d'hospitalisation inconnu '" . $umMode . "' ";
                            $commentaire = " Le code C (Hospitalisation complète) sera utilisé pour cette unité médicale";
                            controle_add_error("MOD", $no_ligne, "Mode d'hospitalisation", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, 27, 1);
                        }
                        break;
                        
                    case 2 :
                    
                        $autStart    = 13;
                        $autLength   = 2;
                        $dateStart   = 15;
                    
                        $umCode      = trim(substr($buffer, 0, 4));
                        $umFiness    = trim(substr($buffer, 4, 9));
                        $umAut       = trim(substr($buffer, $autStart, $autLength));
                        $umDate      = trim(substr($buffer, $dateStart, 8));
                        $umNbLits    = trim(substr($buffer, 23, 3));
                        $umMode      = '';
                        break;
                        
                    case 1 : 
                    
                        $autStart    = 4;
                        $autLength   = 2;
                        $dateStart   = 6;
                    
                        $umCode      = trim(substr($buffer, 0, 4));
                        $umFiness    = '';
                        $umAut       = trim(substr($buffer, $autStart, $autLength));
                        $umDate      = trim(substr($buffer, $dateStart, 8));
                        $umNbLits    = trim(substr($buffer, 14, 3));
                        $umMode      = '';
                        break;
                }
                
                if (array_key_exists($umCode, $unites_medicales) === false) {
                    
                    $erreur = " Code unité médicale inconnu '" . $umCode . "' ";
                    $commentaire = " Le code sera ajouté en base";
                    controle_add_error("UM", $no_ligne, "Unité médicale", $buffer, $erreur, 0, $commentaire, $nbI, $nbW, $nbE, 0, 4);
                }
                if (in_array($umAut, $types_autorisation) === false) {
                    
                    $erreur = " Type autorisation inconnu '" . $umAut . "' ";
                    $commentaire = " Le code sera ajouté en base";
                    controle_add_error("AUT", $no_ligne, "Type autorisation", $buffer, $erreur, 0, $commentaire, $nbI, $nbW, $nbE, $autStart, $autLength);
                }
                if (! controle_check_date($umDate, $erreur, $commentaire)) {
                    
                    $erreur = " Date erronée '" . $umDate . "' ";
                    $commentaire = " La date 01-01-2012 sera prise en remplacement";
                    controle_add_error("DDA", $no_ligne, "Date début autorisation", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $dateStart, 8);
                }
            }
        }
        
        if ($nbE > 0 || $nbW > 0) {
            
            $sqlcmd = " UPDATE pmsi.p_imports SET 
                            nb_erreurs = nb_erreurs + $nbE, 
                            nb_avertissements = nb_avertissements + $nbW 
                        WHERE oid = $import_id ";
            $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
        }
        
        fclose($handle);
    }
    else {
        logWarnMsg("PROBLEME DE LECTURE DU FICHIER DES UNITES MEDICALES");
    }
    logInfoMsg("FIN CONTROLE DES UNITES MEDICALES. Version du fichier $version, $no_ligne lus, $nbI informations, $nbW avertissements, $nbE erreurs graves");
}


function generation_ium() {
    
    global $file_exists_IUM;
    global $file_IUM;
    global $iCTI_connexion;
    global $import_id;
    
    if (!$file_exists_IUM) {
        logInfoMsg("FICHIER DES UM ABSENT OU ILLISIBLE");
        return;
    }
    else {
        logInfoMsg("GENERATION DES UM");
    }
    
    $no_ligne = 0;
    $autStart = 0;
    $autLength = 0;
    $dateStart = 0;
    
    // Détermine la version du fichiers des IUM en fonction de la longueur max des lignes d'enregistrement
    $f = file_get_contents($file_IUM);
    $a = explode(PHP_EOL, $f);
    $max = 0;
    foreach($a as $line) {
        if (strlen($line) > $max) { $max = strlen($line);}
    }
    if ($max >= 28) {
        $version = 3;
    }
    else if ($max >= 26) {
        $version = 2;
    }
    else {
        $version = 1;
    }
    
    $handle = fopen($file_IUM, "r");
    if ($handle) {
        
        // Récupère les données présentes en base pour les unités médicales, les types d'autorisation et les modes d'hospitalisation
        $modes_hospitalisation = get_modes_hospitalisation();
        
        // Mise en place de la table temporaire où sont stockées les données du fichier des unités médicales
        $sqlcmd = " DROP TABLE IF EXISTS temp.t_unites_medicales; 
                    CREATE TABLE temp.t_unites_medicales (
                        code text, 
                        finess text, 
                        type_autorisation text, 
                        date_effet date, 
                        nb_lits numeric, 
                        mode_hospitalisation text);
                    INSERT INTO temp.t_unites_medicales VALUES ";
        $values = array();
        
        while (!feof($handle)) {
            
            $buffer = fgets($handle, 99999);
            
            $no_ligne++;
            
            if (trim($buffer) != "" && $no_ligne < 10000000000000 ) {
                
                switch ($version) {
                    
                    case  3 :
                    
                        $umCode      = trim(substr($buffer, 0, 4));
                        $umFiness    = trim(substr($buffer, 4, 9));
                        $umAut       = trim(substr($buffer, 13, 3));
                        $umDate      = trim(substr($buffer, 16, 8));
                        $umNbLits    = (int)trim(substr($buffer, 24, 3));
                        $umMode      = trim(substr($buffer, 27, 1));
                        
                        // Force le mode d'hospitalisation sur "complète" si celui lu est inconnu
                        if (in_array($umMode, $modes_hospitalisation) === false) {
                            $umMode = 'C';
                        }
                        break;
                    
                    case  2 :
                
                        $umCode      = trim(substr($buffer, 0, 4));
                        $umFiness    = trim(substr($buffer, 4, 9));
                        $umAut       = trim(substr($buffer, 13, 2));
                        $umDate      = trim(substr($buffer, 15, 8));
                        $umNbLits    = (int)trim(substr($buffer, 23, 3));
                        $umMode      = '';
                        break;
                    
                    case  1 :
                
                        $umCode      = trim(substr($buffer, 0, 4));
                        $umFiness    = '';
                        $umAut       = trim(substr($buffer, 4, 2));
                        $umDate      = trim(substr($buffer, 6, 8));
                        $umNbLits    = trim(substr($buffer, 14, 3)) + 0;
                        $umMode      = '';
                        break;
                }
                
                // Force la date au 01 janvier 2012 si la date saisie dans le fichier est incorrecte
                if (! controle_check_date($umDate, $erreur, $commentaire)) {
                    $umDate = '01012012';
                }
                                
                $values[] = " ('" . 
                            $umCode     . "'::text, '" . 
                            $umFiness   . "'::text, '" . 
                            $umAut      . "'::text, to_date('" . 
                            $umDate     . "'::text, 'DDMMYYYY'::text), " .
                            $umNbLits   . "::bigint, '" .
                            $umMode     . "'::text) ";
            }
        }
        
        if (count($values) > 0) {
            
            $sqlcmd .= implode(", ", $values);
            
            $result = $iCTI_connexion->query($sqlcmd);
            if (!is_resource($result)) {
                logWarnMsg("PROBLEME CREATION DE LA TABLE TEMPORAIRE DES UNITES MEDICALES");
            }
            else {
                // Ajout des nouveaux types d'autorisation si trouvés dans le fichier
                $sqlcmd = " INSERT INTO pmsi.t_types_autorisations (code, texte, texte_court)
                            SELECT w_um.type_autorisation, w_um.type_autorisation, w_um.type_autorisation
                            FROM temp.t_unites_medicales w_um
                            LEFT JOIN pmsi.t_types_autorisations ON t_types_autorisations.code = w_um.type_autorisation
                            WHERE t_types_autorisations.code IS NULL; ";
                $result = $iCTI_connexion->query($sqlcmd);
                $nb_new_auth = (is_resource($result) == true) ? pg_affected_rows($result) : 0;
                
                // Mise à jour des infos des UM
                $sqlcmd = " UPDATE pmsi.t_unites_medicales SET
                                type_autorisation = w_um.type_autorisation,
                                date_effet_autorisation = w_um.date_effet,
                                nb_lits = w_um.nb_lits,
                                mode_hospitalisation = w_um.mode_hospitalisation,
                                finess_geographique = w_um.finess
                            FROM temp.t_unites_medicales w_um
                            WHERE 
                                t_unites_medicales.code = w_um.code
                                AND (
                                    t_unites_medicales.type_autorisation IS DISTINCT FROM w_um.type_autorisation OR
                                    t_unites_medicales.date_effet_autorisation IS DISTINCT FROM w_um.date_effet OR
                                    t_unites_medicales.nb_lits IS DISTINCT FROM w_um.nb_lits OR
                                    t_unites_medicales.mode_hospitalisation IS DISTINCT FROM w_um.mode_hospitalisation OR
                                    t_unites_medicales.finess_geographique IS DISTINCT FROM w_um.finess
                                ); ";
                $result = $iCTI_connexion->query($sqlcmd);
                $nb_updates = (is_resource($result) == true) ? pg_affected_rows($result) : 0;
                
                // Ajout des nouvelles unités médicales
                $sqlcmd = " INSERT INTO pmsi.t_unites_medicales (code, texte, type_autorisation, date_effet_autorisation, nb_lits, mode_hospitalisation, finess_geographique)
                            SELECT
                                w_um.code,
                                w_um.code,
                                w_um.type_autorisation,
                                w_um.date_effet,
                                w_um.nb_lits,
                                w_um.mode_hospitalisation,
                                w_um.finess
                            FROM
                                temp.t_unites_medicales w_um
                                LEFT JOIN pmsi.t_unites_medicales ON t_unites_medicales.code = w_um.code
                            WHERE
                                t_unites_medicales.code IS NULL;
                            
                            SELECT pmsi.cti_update_schema_classes('UM');
                ";
                $result = $iCTI_connexion->query($sqlcmd);
                $nb_new_um = (is_resource($result) == true) ? pg_affected_rows($result) : 0;
            }
        }
        else {
            logWarnMsg("FICHIER DES UNITES MEDICALES VIDE");
        }
        
        fclose($handle);
    }
    else {
        logWarnMsg("PROBLEME DE LECTURE DU FICHIER DES UNITES MEDICALES");
    }
    
    logInfoMsg("FIN CONTROLE DES UM. version $version. $no_ligne lus, $nb_new_auth type(s) d'aut. créé(s), $nb_updates um modfiée(s), $nb_new_um  um créée(s)");
}


function controle_rum() {


    global $ENV_FINESS;
    global $ENV_TYPEETS;
    
    global $import_id;

    global $file_RSS;
    global $file_RSF;

    global $file_exists_RSSMED;
    global $file_exists_RSSNOM;
    global $file_exists_ACTMED;
    global $file_exists_RSS;
    global $file_exists_RSF;

    global $rssmed_array;
    global $rssnom_array;
    global $actmed_array;
    
    global $rssmed_deja;
    global $rssnom_deja;
    
    global $current_rsfa_index;
    
    global $versions_groupage;
    

    logInfoMsg("CONTROLE DES RUM");

    $nb = 0;
    $nbI = 0;
    $nbW = 0;
    $nbE = 0;
    
    begin_trans();

    
    if ($file_exists_RSS) {
        
        // recherche des RSS dans les RSF
        $rsss_array = array();
        $rsss_ghs_array = array();

        if ($file_exists_RSF && $ENV_TYPEETS == "1") {
            $handle = @fopen($file_RSF, "r");
            $current_rsfa_index = 0;
            
            if ($handle) {
                while (!feof($handle)) {
                    $buffer = fgets($handle, 99999);
                    
                    if (trim($buffer) != "" ) {

                        $BUF_record = read_rsf_partial_line($buffer);
                        
                        if ($BUF_record["ok"] == TRUE) {

                            // ENTETE RSF
                            if ($BUF_record["type_enregistrement"] == "A") {
                            
                                
                                
                                // RSS
                                if (controle_check_num($BUF_record["no_rss"],0,FALSE,$erreur,$commentaire)) {
                                    $no_rss = get_numrss($BUF_record["no_rss"]);
                                    $rsss_array[$no_rss] = "OK";
                                    //$rsss_ghs_array[$no_rss] = "";
                                }

                            }
                            
                            // prestation principale  GHS
                            if ($BUF_record["type_enregistrement"] == "B") {
                                
                                // RSS
                                if ($BUF_record["code_acte"] == "GHS") {
                                    $no_rss = get_numrss($BUF_record["no_rss"]);
                                    $rsss_ghs_array[$no_rss] = "GHS";
                                }
                                
                            }
                            
                        }
                        
                    }
                    
                }
                
            }
        }
        
        $no_ligne = 0;
        $dates_array = array();
        $ok_rss_array = array();
        
        $nb_rss = 0;
        $nb_rum = 0;
        
        $finess_error = FALSE;
        $format_error = FALSE;
        $finess_first = "";
        
        $nb_errors_rss_med = 0;
        $nb_errors_rss_nom = 0;
        
        $handle = @fopen($file_RSS, "r");
        if ($handle) {
            while (!feof($handle)) {
                $buffer = fgets($handle, 99999);
                
                $no_ligne++;
                if (trim($buffer) != "" && $no_ligne < 1000000000000000) {
                
                    $nb++;
                    
                    $BUF_record = read_rum_line($buffer);
                    if ($BUF_record["type_enregistrement"] == "RUM") {
                    
                        $BUF_offsets = $BUF_record["BUF_offsets"];
                        
                        $no_rss = get_numrss($BUF_record["no_rss"]);
                        
                        $rss_ok = TRUE;
                        
                        if ($rss_ok == TRUE) {
                    
                            $nb_rum++;
                            
                            $decalage = FALSE;
                            $rss_error = FALSE;
                            
                            if ($BUF_record["fmt_error"] != "" && $format_error == FALSE) {
                                $erreur = $BUF_record["fmt_error"];
                                $commentaire = "Le fichier est accepté par iCTI mais ne peut être envoyé aux tutelles";
                                controle_add_error("RSS", $no_ligne, "Format", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["version_format_offset"], $BUF_offsets["version_format_len"]);
                                $format_error = TRUE;
                            }
                        
                            // Finess
                            if (1 == 2) {
                            if ($BUF_record["finess"] != $ENV_FINESS && $finess_error == FALSE) {
                                $erreur = "Valeur " . $BUF_record["finess"] . " différente de $ENV_FINESS";
                                $commentaire = "Le fichier est erroné";
                                controle_add_error("RSS", $no_ligne, "Finess", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["finess_offset"], $BUF_offsets["finess_len"]);
                                $finess_error = TRUE;
                            }
                            }
                            if ($finess_first == "") {
                                $finess_first = $BUF_record["finess"];
                            }
                            
                            // date naissance non numérique(si erreur, décalage)
                            if ($decalage == FALSE) {
                                if (! controle_check_num($BUF_record["date_naissance"],8,FALSE,$erreur,$commentaire)) {
                                    $erreur = "Date de naissance non numérique pour RSS " . $BUF_record["no_rss"];
                                    $commentaire = "Il y a peut-être un décalage dans l'enregistrement";
                                    controle_add_error("RSS", $no_ligne, "Date naissance", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["date_naissance_offset"], $BUF_offsets["date_naissance_len"]);
                                    $decalage = TRUE;
                                }
                            }
                            
                            // Code sexe (si erreur, décalage)
                            if ($decalage == FALSE) {
                                $sexe = $BUF_record["sexe"];
                                if ($sexe != "1" && $sexe != "2" && $sexe != "3" ) {
                                    $erreur = "Valeur $sexe incorrecte pour RSS " . $BUF_record["no_rss"];
                                    $commentaire = "Il y a peut-être un décalage dans l'enregistrement";
                                    controle_add_error("RSS", $no_ligne, "Sexe", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["sexe_offset"], $BUF_offsets["sexe_len"]);
                                    $decalage = TRUE;
                                }
                            }
                            
                            // date entree non numérique(si erreur, décalage)
                            if ($decalage == FALSE) {
                                if (! controle_check_num($BUF_record["date_entree"],8,FALSE,$erreur,$commentaire)) {
                                    $erreur = "Date d'entrée non numérique pour RSS " . $BUF_record["no_rss"];
                                    $commentaire = "Il y a peut-être un décalage dans l'enregistrement";
                                    controle_add_error("RSS", $no_ligne, "Date entree", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["date_entree_offset"], $BUF_offsets["date_entree_len"]);
                                    $decalage = TRUE;
                                }
                            }
                            
                            
                            
                            if ($decalage == FALSE) {
                            
                                $ok_rss_array[$no_rss] = $no_rss;
                            
                                // version groupage
                                $version_groupage = strtoupper($BUF_record["version_groupage"]);
                                if ($BUF_record["ghm"] != "") {
                                    if (!in_array($version_groupage, $versions_groupage)) {
                                        $erreur = "Valeur $version_groupage incorrecte pour RSS " . $BUF_record["no_rss"];
                                        $commentaire = "";
                                        controle_add_error("RSS", $no_ligne, "Version groupage", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["version_groupage_offset"], $BUF_offsets["version_groupage_len"]);
                                    }
                                }
                                
                                // GHM

                                if ($BUF_record["ghm"] != "") {
                                    if (! check_ghm($BUF_record["ghm"], $gravite, $erreur, $commentaire)) {
                                        $erreur = $erreur . " pour RSS " . $BUF_record["no_rss"];
                                        controle_add_error("RSS", $no_ligne, "GHM", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["ghm_offset"], $BUF_offsets["ghm_len"]);
                                    }

                                }
                                else {
                                    if ($file_exists_RSF) {
                                        $no_rss = get_numrss($BUF_record["no_rss"]);
                                        $in_rsf = "";
                                        $in_rsf = @$rsss_array[$no_rss];
                                        if ($in_rsf == "OK") {
                                            if (@$rsss_ghs_array[$no_rss] == "GHS") {;
                                                $erreur = "Pas de GHM pour RSS " . $BUF_record["no_rss"];
                                                $commentaire = "";
                                                controle_add_error("RSS", $no_ligne, "GHM", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["ghm_offset"], $BUF_offsets["ghm_len"]);
                                            }
                                        }
                                    }
                                    
                                }
                                
                                
                                // RSS
                                if (! controle_check_num($BUF_record["no_rss"],0,FALSE,$erreur,$commentaire)) {
                                    $commentaire = "";
                                    controle_add_error("RSS", $no_ligne, "Numéro RSS", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["no_rss_offset"], $BUF_offsets["no_rss_len"]);
                                    $rss_error = TRUE;
                                }
                                else {
                                    if ($file_exists_RSF && $ENV_TYPEETS == "1") {
                                        $no_rss = get_numrss($BUF_record["no_rss"]);
                                        $in_rsf = "";
                                        $in_rsf = @$rsss_array[$no_rss];
                                        if ($in_rsf != "OK") {
                                            $erreur = "Aucun RSF pour le RSS " . $BUF_record["no_rss"] ;
                                            $commentaire = "Ce RSS ne sera pas récupéré";
                                            controle_add_error("RSS", $no_ligne, "Numéro RSS", $buffer, $erreur, 3, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["no_rss_offset"], $BUF_offsets["no_rss_len"]);
                                        }
                                    }
                                }

                                
                                // date naissance
                                if (! controle_check_date($BUF_record["date_naissance"],$erreur,$commentaire, true)) {
                                    $commentaire = default_birth_date($BUF_record["date_naissance"]) . " prise par défaut";
                                    controle_add_error("RSS", $no_ligne, "Date naissance", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["date_naissance_offset"], $BUF_offsets["date_naissance_len"]);
                                }
                                
                                
                                
                                // Date entree
                                if (! controle_check_date($BUF_record["date_entree"],$erreur,$commentaire)) {
                                    $commentaire = "";
                                    controle_add_error("RSS", $no_ligne, "Date entrée", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["date_entree_offset"], $BUF_offsets["date_entree_len"]);
                                }
                                
                                // mode entrée
                                if (! check_mode_entree($BUF_record["mode_entree"], $gravite, $erreur, $commentaire)) {
                                    controle_add_error("RSS", $no_ligne, "Mode entrée", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["mode_entree_offset"], $BUF_offsets["mode_entree_len"]);
                                }
                                
                                // Provenance
                                if (! check_provenance($BUF_record["provenance"], $gravite, $erreur, $commentaire)) {
                                    controle_add_error("RSS", $no_ligne, "Provenance", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["provenance_offset"], $BUF_offsets["provenance_len"]);
                                }

                                // Passage Urgences
                                if (! check_passage_urgences($BUF_record["passage_urgences"], $gravite, $erreur, $commentaire)) {
                                    controle_add_error("RSS", $no_ligne, "Passage Urgences", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["passage_urgences_offset"], $BUF_offsets["passage_urgences_len"]);
                                }
                                          
                                // Date sortie
                                if (! controle_check_date($BUF_record["date_sortie"],$erreur,$commentaire)) {
                                    $commentaire = "";
                                    controle_add_error("RSS", $no_ligne, "Date sortie", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["date_sortie_offset"], $BUF_offsets["date_sortie_len"]);
                                }
                                else {
                                    $dates_array[$BUF_record["no_rss"]] = sqlDate($BUF_record["date_sortie"]);
                                }
                                
                                // Mode sortie
                                if (! check_mode_sortie($BUF_record["mode_sortie"], $gravite, $erreur, $commentaire)) {
                                    controle_add_error("RSS", $no_ligne, "Mode sortie", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["mode_sortie_offset"], $BUF_offsets["mode_sortie_len"]);
                                }
                                
                                // Destination
                                if (! check_destination($BUF_record["destination"], $gravite, $erreur, $commentaire)) {
                                    controle_add_error("RSS", $no_ligne, "destination", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["destination_offset"], $BUF_offsets["destination_len"]);
                                }
                                
                                
                                // Code postal
                                if (! controle_check_num($BUF_record["code_postal"],5,FALSE,$erreur,$commentaire)) {
                                    $commentaire = "";
                                    if (strlen($BUF_record["code_postal"]) < 5) {
                                        $commentaire = "Valeur " . substr($BUF_record["code_postal"] . "00000" , 0, 5) . " prise en remplacement";
                                    }
                                    controle_add_error("RSS", $no_ligne, "Code postal", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["code_postal_offset"], $BUF_offsets["code_postal_len"]);
                                }

                                // Poids bébé
                                if (! controle_check_num($BUF_record["poids_bebe"],4, TRUE,$erreur,$commentaire)) {
                                    $commentaire = "0 pris par défaut";
                                    controle_add_error("RSS", $no_ligne, "Poids bebe", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["poids_bebe_offset"], $BUF_offsets["poids_bebe_len"]);
                                }

                                
                                
                                // Nombre séances
                                if (! controle_check_num($BUF_record["nombre_seances"],2, TRUE,$erreur,$commentaire)) {
                                    $commentaire = "0 pris par défaut";
                                    controle_add_error("RSS", $no_ligne, "Nombre séances", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["nombre_seances_offset"], $BUF_offsets["nombre_seances_len"]);
                                }
                                
                                // Nombre diagnostics
                                if (! controle_check_num($BUF_record["nombre_diagnostics"],2, FALSE,$erreur,$commentaire)) {
                                    $commentaire = "";
                                    controle_add_error("RSS", $no_ligne, "Nombre diagnostics", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["nombre_diagnostics_offset"], $BUF_offsets["nombre_diagnostics_len"]);
                                }
                                
                                // Nombre actes
                                if (! controle_check_num($BUF_record["nombre_actes"],0, FALSE,$erreur,$commentaire)) {
                                    $commentaire = "0 pris par défaut";
                                    controle_add_error("RSS", $no_ligne, "Nombre actes", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["nombre_actes_offset"], $BUF_offsets["nombre_actes_len"]);
                                }
                                
                                // Age gestationnel
                                if (! controle_check_num($BUF_record["age_gestationnel"],2, TRUE,$erreur,$commentaire)) {
                                    $commentaire = "";
                                    controle_add_error("RSS", $no_ligne, "Age gestationnel", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["nombre_actes_offset"], $BUF_offsets["nombre_actes_len"]);
                                }

                                
                                // Date dernieres regles
                                /*if (! controle_check_date($BUF_record["date_dernieres_regles"],$erreur,$commentaire)) {
                                    $commentaire = "";
                                    controle_add_error("RSS", $no_ligne, "Date dernieres regles", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["date_entree_offset"], $BUF_offsets["date_entree_len"]);
                                }*/
                                
                                // Confirmation codage
                                //$BUF_record["confirmation_codage"]
                                
                                // Type machine rdth
                                //$BUF_record["type_machine_rdth"]
                                
                                // Type dosimetrie
                                //$BUF_record["type_dosimetrie"]
                                
                                // Numero innovation
                                // désactivé par CLA le 15-05-2017 car le numéro d'innovation peut être alphanumérique (voir format RSS)
                                // if (! controle_check_num($BUF_record["numero_innovation"], 15, TRUE, $erreur, $commentaire)) {
                                    // $commentaire = "";
                                    // controle_add_error("RSS", $no_ligne, "Numero innovation", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["nombre_actes_offset"], $BUF_offsets["nombre_actes_len"]);
                                // }
                                
                                // diagnostic principal
                                if (trim($BUF_record["diagnostic_principal"]) == "") {
                                    if ($BUF_record["ghm"] != "") {
                                    if (@$rsss_ghs_array[$no_rss] == "GHS") {;
                                        $erreur = "Pas de diagnostic principal";
                                        $commentaire = "";
                                        controle_add_error("RSS", $no_ligne, "Diagnostic principal", $buffer, $erreur, 3, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["diagnostic_principal_offset"], $BUF_offsets["diagnostic_principal_len"]);
                                    }
                                    }
                                }
                                else {
                                    if (! check_diagnostic($BUF_record["diagnostic_principal"], $gravite, $erreur, $commentaire)) {
                                        controle_add_error("RSS", $no_ligne, "Diagnostic principal", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["diagnostic_principal_offset"], $BUF_offsets["diagnostic_principal_len"]);
                                    }
                                }

                                // Diagnostic relie
                                if ($BUF_record["diagnostic_relie"] != "") {
                                    if (! check_diagnostic($BUF_record["diagnostic_relie"], $gravite, $erreur, $commentaire)) {
                                        controle_add_error("RSS", $no_ligne, "Diagnostic relié", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["diagnostic_relie_offset"], $BUF_offsets["diagnostic_relie_len"]);
                                    }
                                }
                                
                                // IGS
                                if (! controle_check_num($BUF_record["igs2"],3, TRUE,$erreur,$commentaire)) {
                                    $commentaire = "0 pris par défaut";
                                    controle_add_error("RSS", $no_ligne, "IGS 2", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["igs2_offset"], $BUF_offsets["igs2_len"]);
                                }
                                
                                // Medecin RSS
                                
                                if ($rss_error == FALSE) {
                                    if ($file_exists_RSSMED) {
                                        $code_med = "";
                                        $code_med = @$rssmed_array[$no_rss];
                                        if ($code_med == "") {
                                            if (strpos($rssmed_deja, ", $no_rss,") === FALSE) {
                                                $nb_errors_rss_med++;
                                                //$erreur = "Association RSS-Médecin inexistante pour RSS " . $BUF_record["no_rss"];
                                                //$commentaire = "";
                                                //controle_add_error("RSS", $no_ligne, "Numéro RSS", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["no_rss_offset"], $BUF_offsets["no_rss_len"]);
                                            }
                                        }
                                    }
                                }
                                
                                // Nom RSS
                                if ($rss_error == FALSE) {
                                    if ($file_exists_RSSNOM) {
                                        $nom = "";
                                        $nom = @$rssnom_array[$no_rss];
                                        if ($nom == "") {
                                            if (strpos($rssnom_deja, ", $no_rss,") === FALSE) {
                                                $nb_errors_rss_nom++;
                                                //$erreur = "Association RSS-Nom inexistante pour RSS " . $BUF_record["no_rss"];
                                                //$commentaire = "";
                                                //controle_add_error("RSS", $no_ligne, "Numéro RSS", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["no_rss_offset"], $BUF_offsets["no_rss_len"]);
                                            }
                                        }
                                    }
                                }
                                
                                // Diagnostics associés
                                $di = 0;
                                foreach ($BUF_record["diags"] as $diagnostic_associe) {
                                    $di++;
                                    if (! check_diagnostic($diagnostic_associe, $gravite, $erreur, $commentaire)) {
                                        controle_add_error("RSS", $no_ligne, "Diagnostic associé $di", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_record["diags_offset"][$di], $BUF_record["diags_len"][$di]);
                                    }
                                }
                                
                                // Diagnostics à visé documentaire
                                $dd = 0;
                                foreach ($BUF_record["diagsdoc"] as $diagnostic_documentaire) {
                                    $dd++;
                                    if (! check_diagnostic($diagnostic_documentaire, $gravite, $erreur, $commentaire)) {
                                        controle_add_error("RSS", $no_ligne, "Diagnostic documentaire $dd", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_record["diagsdoc_offset"][$dd], $BUF_record["diagsdoc_len"][$dd]);
                                    }
                                }
                                

                                // Actes
                                $ac = 0;
                                foreach ($BUF_record["actes"] as $BUF_acte) {
                                    $ac++;
                                    $BUF_code_acte = trim(substr($BUF_acte , 8, 7));
                                    $BUF_extension_atih = ((intval($BUF_record["version_format"]) >= 117) && trim(substr($BUF_acte , 15, 3)) != '-00') ? trim(substr($BUF_acte , 15, 3)) : "";
                                    $BUF_code_acte .= $BUF_extension_atih;
                                    $BUF_date_acte = trim(substr($BUF_acte , 0, 8));
                                    $BUF_activite_ccam = trim(substr($BUF_acte , 16 + $BUF_record["offset_format"], 1));

                                    $BUF_modificateurs = trim(substr($BUF_acte,18 + $BUF_record["offset_format"],4)); // recuperer les 4 modificateurs lu dans le buffer acte
                                    $array_modificateurs = str_split($BUF_modificateurs,1);//transferer la chaine lue de taille 4 à un tableau

                                    for ($i=0; $i <4 ; $i++) {
                                        if (isset($array_modificateurs[$i]) && !check_modificateur($array_modificateurs[$i],$gravite, $erreur, $commentaire)) {
                                            controle_add_error("RSS",$no_ligne,"Acte modificateur $ac", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_record["actes_offset"][$ac], $BUF_record["actes_len"][$ac]);
                                        }
                                     }

                                    if (! check_acte($BUF_code_acte , $gravite, $erreur, $commentaire)) {
                                        controle_add_error("RSS", $no_ligne, "Acte $ac", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_record["actes_offset"][$ac], $BUF_record["actes_len"][$ac]);
                                    }
                                    else {
                                        // Medecin acte
                                        if ($rss_error == FALSE) {
                                            if ($file_exists_ACTMED) {
                                                $cle = get_numrss($BUF_record["no_rss"]);
                                                $cle = $cle . $BUF_code_acte;
                                                $cle = $cle . get_date_AAAAMMJJ($BUF_date_acte);
                                                $cle = $cle . $BUF_activite_ccam;
                                                $code_med = "";
                                                $code_med = $actmed_array[$cle];
                                                if ($code_med == "") {
                                                    $cle = get_numrss($BUF_record["no_rss"]);
                                                    $cle = $cle . $BUF_code_acte;
                                                    $cle = $cle . "00000000";
                                                    $cle = $cle . $BUF_activite_ccam;
                                                    $code_med = "";
                                                    $code_med = $actmed_array[$cle];
                                                }
                                                if ($code_med == "" && ($BUF_code_acte == "AFLB010" || $BUF_code_acte == "ZZLP025" || $BUF_code_acte == "ZZLP054")) {
                                                    $cle = get_numrss($BUF_record["no_rss"]);
                                                    $cle = $cle . $BUF_code_acte;
                                                    $cle = $cle . "00000000";
                                                    $cle = $cle . "4";
                                                    $code_med = "";
                                                    $code_med = $actmed_array[$cle];
                                                }
                                                if ($code_med == "") {
                                                    //$erreur = "Association Acte-Exécutant inexistante pour RSS " . $BUF_record["no_rss"] . " acte " . $BUF_code_acte . "-" . $BUF_activite_ccam;
                                                    //$commentaire = "";
                                                    //controle_add_error("RSS", $no_ligne, "Code acte CCAM", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_record["actes_offset"][$ac], $BUF_record["actes_len"][$ac]);
                                                }
                                            }
                                        }
                                    }
                                }

                            }
                        
                        }
                        
                        // Date sortie
                        if (controle_check_date($BUF_record["date_sortie"],$erreur,$commentaire)) {
                            $dates_array[$BUF_record["no_rss"]] = sqlDate($BUF_record["date_sortie"]);
                        }
                        
                    }
                }
            
            }
            
            fclose($handle);
        
        }
        
        // comptage RSS
        foreach ($ok_rss_array as $no_rss) {
            $nb_rss++;
        }
    
        // période
        $date_sortie_1 = "2099-12-31";
        $date_sortie_9 = "0001-01-01";
        
        foreach ($dates_array as $date_sortie) {

            if ($date_sortie < $date_sortie_1) {
                $date_sortie_1 = $date_sortie;
            }
            if ($date_sortie > $date_sortie_9) {
                $date_sortie_9 = $date_sortie;
            }

        }
        
    
        logInfoMsg("Période de sortie du $date_sortie_1 au $date_sortie_9");
        if (substr($date_sortie_1,0,4) != substr($date_sortie_9,0,4)) {
		if (substr($date_sortie_9,0,4) != "0001") {
            controle_add_error("FILE", 0, "", "", "Année de début différente de l'année de fin", 4, "", $nbI, $nbW, $nbE);
            logWarnMsg("Année de début différente de l'année de fin");
        }
		}
        
        if ($nb_errors_rss_nom++ > 0) {
            controle_add_error("RSS", 0, "", "", "$nb_errors_rss_nom RSS sans nom associé", 1, "", $nbI, $nbW, $nbE);
        }
        if ($nb_errors_rss_med++ > 0) {
            controle_add_error("RSS", 0, "", "", "$nb_errors_rss_med RSS sans médecin associé", 1, "", $nbI, $nbW, $nbE);
        }
        

        $sqlcmd = "UPDATE pmsi.p_imports SET ";
        $sqlcmd = $sqlcmd . "finess = '$finess_first',  ";
        $sqlcmd = $sqlcmd . "nb_rss = $nb_rss, nb_rum = $nb_rum,  ";
        $sqlcmd = $sqlcmd . "date_debut = '$date_sortie_1', ";
        $sqlcmd = $sqlcmd . "date_fin = '$date_sortie_9' ";
        $sqlcmd = $sqlcmd . "WHERE oid = $import_id";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
		
		// Si pas de RSS (cas de l'autodialyse Parc Monceau), il faut positionner les dates selon le nom du fichier
		$sqlcmd = "UPDATE pmsi.p_imports
				SET finess = subview.finess,
					date_debut = subview.date_debut,
					date_fin = subview.date_fin
				FROM
				(
				SELECT p_imports.oid, file_path,
					split_part(file_path,'.',1) AS finess,
					(split_part(file_path,'.',2)||'/01/01')::date AS date_debut,
					date((split_part(file_path,'.',2)||'/'||split_part(file_path,'.',3)||'/01')::date+interval '1 month' - interval '1 day') AS date_fin
				FROM pmsi.p_imports
				JOIN pmsi.p_imports_data ON import_id = p_imports.oid
				JOIN base.t_finess ON split_part(file_path,'.',1) = t_finess.code
				WHERE p_imports_data.data_type = 'ZIN' AND
					split_part(file_path,'.',2) LIKE '20%' AND
					p_imports.oid = $import_id AND
					p_imports.date_fin = '00010101'
				) subview
				WHERE p_imports.oid = subview.oid";
		$toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );	
    
    }
    
    else {
        controle_add_error("FILE", 0, "", "", "Fichier des RSS absent", 4, "", $nbI, $nbW, $nbE);
    
    }
    
    
    if ($nbE > 0 || $nbW > 0) {

        $sqlcmd = "UPDATE pmsi.p_imports SET ";
        $sqlcmd = $sqlcmd . "nb_erreurs = nb_erreurs + $nbE, nb_avertissements = nb_avertissements + $nbW ";
        $sqlcmd = $sqlcmd . "WHERE oid = $import_id";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );

    }
    
    
    commit_trans();
    
    logInfoMsg("FIN CONTROLE DES RUM. $nb lus, $nbI informations, $nbW avertissements, $nbE erreurs graves");
    
}


function controle_rsf() {

    
    global $ENDSTATUS;
    global $iCTI_connexion;
    global $ENV_FINESS;
    global $ENV_TYPEETS;
    
    global $import_id;
    global $ENV_PMSIPROVIDER;
    global $ENV_PMSIPROVIDER2;

    global $file_RSS;
    global $file_RSF;

    global $file_exists_ACTMED;
    global $file_exists_RSS;
    global $file_exists_RSF;
    
    global $actmed_array;
    
    global $current_rsfa_index;

    logInfoMsg("CONTROLE DES RSF");
    
    $w_ENV_PMSIPROVIDER = $ENV_PMSIPROVIDER;

    $nb = 0;
    $nbI = 0;
    $nbW = 0;
    $nbE = 0;
    $no_ligne = 0;

    $nb_rsf = 0;
    
    begin_trans();
    
    $finess_error = FALSE;
    
    if ($file_exists_RSF) {
    
        // recherche des RSF dans les RUM
        $rsss_array = array();

        if ($file_exists_RSS) {
            $handle = @fopen($file_RSS, "r");
            if ($handle) {
                while (!feof($handle)) {
                    $buffer = fgets($handle, 99999);
                    
                    $no_ligne++;
                    if (trim($buffer) != "" && $no_ligne < 100000000000) {
                    
                        $nb++;
                        
                        $BUF_record = read_rum_partial_line($buffer);
                        
                        if ($BUF_record["type_enregistrement"] == "RUM") {
                                
                            // RSS
                            if (controle_check_num($BUF_record["no_rss"],0,FALSE,$erreur,$commentaire)) {
                                $no_rss = get_numrss($BUF_record["no_rss"]);
                                $rsss_array[$no_rss] = "OK";
                            }
                            
                        }
                        
                    }
                    
                }
                
            }
        }
        
        
        $no_ligne = 0;
        $type_rss = "";
        $rss_ok = TRUE;
        
        $current_rsfa_index = 0;

        $handle = @fopen($file_RSF, "r");
        if ($handle) {
            while (!feof($handle)) {
                $buffer = fgets($handle, 99999);
                
                $no_ligne++;
                if (trim($buffer) != "" && $no_ligne < 100000000000) {
                
                    $nb++;
                    
                    $BUF_record = read_rsf_line($buffer);
                    
                    if ($BUF_record["ok"] == TRUE) {
                    
                        $BUF_offsets = $BUF_record["BUF_offsets"];

                        // ENTETE RSF
                        if ($BUF_record["type_enregistrement"] == "A") {
                        
                            

                            $type_rss = "";
                            if (get_numrss($BUF_record["no_rss"]) == 0) {
                                // $BUF_record["no_rss"] = $BUF_record["no_facture"] + 99000000000;
                                $BUF_record["no_rss"] = '9' . str_pad(ltrim($BUF_record["no_facture"], '0'), 8, '0', STR_PAD_LEFT);
                            }
                            $no_rss = get_numrss($BUF_record["no_rss"]);
                            
                            
                            $rss_ok = TRUE;
                            
                            if ($rss_ok == TRUE) {
                            
                                $nb_rsf++;
                            
                                // Finess
                                if (1 == 2) {
                                if ($BUF_record["finess"] != $ENV_FINESS && $finess_error == FALSE) {
                                    $erreur = "Valeur " . $BUF_record["finess"] . " différente de $ENV_FINESS";
                                    $commentaire = "Le fichier est erroné";
                                    controle_add_error("RSF", $no_ligne, "Finess", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["finess_offset"], $BUF_offsets["finess_len"]);
                                    $finess_error = TRUE;
                                }
                                }
                                
                                
                                // RSS
                                if (! controle_check_num($BUF_record["no_rss"],0,FALSE,$erreur,$commentaire)) {
                                    $commentaire = "";
                                    controle_add_error("RSF", $no_ligne, "Numéro RSS", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["no_rss_offset"], $BUF_offsets["no_rss_len"]);
                                }
                                
                            
                            
                                // Code sexe
                                $value = $BUF_record["sexe"];
                                if ($value != "1" && $value != "2" && $value != "3" && $value != "4" && $value != "5" ) {
                                    $erreur = "Valeur $value incorrecte";
                                    $commentaire = "1 (masculin) pris par défaut";
                                    controle_add_error("RSF", $no_ligne, "Sexe", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["sexe_offset"], $BUF_offsets["sexe_len"]);
                                }
                                else {
                                    if ($w_ENV_PMSIPROVIDER != "shs") {
                                        if ($value != "1" && $value != "2" && $value != "3" ) {
                                            $erreur = "Valeur $value incorrecte";
                                            $commentaire = "1 (masculin) pris par défaut";
                                            controle_add_error("RSF", $no_ligne, "Sexe", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["sexe_offset"], $BUF_offsets["sexe_len"]);
                                        }
                                    }
                                }
                                
                                
                                // Code civilite
                                if ($BUF_record["nature_operation"] != "" &&  $BUF_record["civilite"] != "" && ($BUF_record["sexe"] == "1" || $BUF_record["sexe"] == "2" || $BUF_record["sexe"] == "3")) {
                                $value = $BUF_record["civilite"];
                                if ($value != "" && $value != "1" && $value != "2" && $value != "3") {
                                    $erreur = "Valeur $value incorrecte";
                                    $commentaire = "3 (SANS) pris par défaut";
                                    controle_add_error("RSF", $no_ligne, "Civilité", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE,  $BUF_offsets["civilite_offset"],  $BUF_offsets["civilite_len"]);
                                }
                                }
                                
                                // Rang bénéficiaire
                                if (! controle_check_num($BUF_record["rang_beneficiaire"],0, TRUE,$erreur,$commentaire)) {
                                    $commentaire = "";
                                    controle_add_error("RSF", $no_ligne, "rang bénéficiaire", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["rang_beneficiaire_offset"], $BUF_offsets["rang_beneficiaire_len"]);
                                }
                                
                                // Nature opération
                                if ($BUF_record["nature_operation"] != "" &&  $BUF_record["civilite"] != "") {
                                $value = $BUF_record["nature_operation"];
                                if ($value != "0" && $value != "1" && $value != "2" && $value != "3" && $value != "4" && $value != "5" && $value != "9" ) {
                                    $erreur = "Valeur $value incorrecte";
                                    $commentaire = "1 pris par défaut";
                                    controle_add_error("RSF", $no_ligne, "Nature opération", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["nature_operation_offset"], $BUF_offsets["nature_operation_len"]);
                                }
                                }
                                
                                // Nature assurance
                                if (! check_nature_pec($BUF_record["nature_assurance"], $gravite, $erreur, $commentaire)) {
                                    controle_add_error("RSF", $no_ligne, "Nature assurance", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["nature_assurance_offset"], $BUF_offsets["nature_assurance_len"]);
                                }
                                
                                
                                                        
                                // Code prise en charge
                                $value = $BUF_record["code_pec"];
                                if ($ENV_TYPEETS == "1") {
                                    if ($value != "0" && $value != "1" && $value != "2" && $value != "3" && $value != "4" && $value != "5" && $value != "") {
                                        $erreur = "Valeur $value incorrecte";
                                        $commentaire = "1 pris par défaut";
                                        controle_add_error("RSF", $no_ligne, "Code prise en charge", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["code_pec_offset"], $BUF_offsets["code_pec_len"]);
                                    }
                                }
                                else {
                                    if ($value != "0" && $value != "1" && $value != "2" && $value != "3" && $value != "X" && $value != "") {
                                        $erreur = "Valeur $value incorrecte";
                                        $commentaire = "1 pris par défaut";
                                        controle_add_error("RSF", $no_ligne, "Code prise en charge", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["code_pec_offset"], $BUF_offsets["code_pec_len"]);
                                    }
                                }
                                
                                // facture
                                if (! controle_check_num($BUF_record["no_facture"],0,TRUE,$erreur,$commentaire)) {
                                    $commentaire = "";
                                    controle_add_error("RSF", $no_ligne, "Numéro facture", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["no_facture_offset"], $BUF_offsets["no_facture_len"]);
                                }
                                
                                // Grand régime
                                if (! check_regime($BUF_record["grand_regime"], $gravite, $erreur, $commentaire)) {
                                    controle_add_error("RSF", $no_ligne, "Grand régime", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["grand_regime_offset"], $BUF_offsets["grand_regime_len"]);
                                }
                                
                                // date naissance
                                if (! controle_check_date($BUF_record["date_naissance"],$erreur,$commentaire, true)) {
                                    $commentaire = default_birth_date($BUF_record["date_naissance"]) . " prise par défaut";
                                    controle_add_error("RSF", $no_ligne, "RSS " . $no_rss . ". Date naissance", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["date_naissance_offset"], $BUF_offsets["date_naissance_len"]);
                                }
                                
                                // Rang naissance
                                if (! controle_check_num($BUF_record["rang_naissance"],1, TRUE,$erreur,$commentaire)) {
                                    $commentaire = "";
                                    controle_add_error("RSF", $no_ligne, "RSS " . $no_rss . ". Rang naissance", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["rang_naissance_offset"], $BUF_offsets["rang_naissance_len"]);
                                }
                                
                                // Date entree
                                if (! controle_check_date($BUF_record["date_entree"],$erreur,$commentaire)) {
                                    $commentaire = "";
                                    controle_add_error("RSF", $no_ligne, "Date entrée", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["date_entree_offset"], $BUF_offsets["date_entree_len"]);
                                }
                                
                                
                                // Date sortie
                                if (! controle_check_date($BUF_record["date_sortie"],$erreur,$commentaire)) {
                                    $commentaire = "";
                                    controle_add_error("RSF", $no_ligne, "Date sortie", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["date_sortie_offset"], $BUF_offsets["date_sortie_len"]);
                                }
                                
                                // base remboursement
                                if (! controle_check_num($BUF_record["base_remboursement_c"],8, FALSE,$erreur,$commentaire)) {
                                    $commentaire = "0 pris par défaut";
                                    controle_add_error("RSF", $no_ligne, "Base remboursement prestations hospitalières", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["base_remboursement_c_offset"], $BUF_offsets["base_remboursement_c_len"]);
                                }
                                
                                // honoraires facturés
                                if (! controle_check_num($BUF_record["total_honoraires_factures"],8, FALSE,$erreur,$commentaire)) {
                                    $commentaire = "0 pris par défaut";
                                    controle_add_error("RSF", $no_ligne, "Total honoraires facturés", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["total_honoraires_factures_offset"], $BUF_offsets["total_honoraires_factures_len"]);
                                }

                                // honoraires remboursables
                                if (! controle_check_num($BUF_record["total_honoraires_remboursable"],8, FALSE,$erreur,$commentaire)) {
                                    $commentaire = "0 pris par défaut";
                                    controle_add_error("RSF", $no_ligne, "Total honoraires remboursable", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["total_honoraires_remboursable_offset"], $BUF_offsets["total_honoraires_remboursable_len"]);
                                }
                                
                                // participation assuré avant OC
                                if (! controle_check_num($BUF_record["total_assure_avant_oc"],8, FALSE,$erreur,$commentaire)) {
                                    $commentaire = "0 pris par défaut";
                                    controle_add_error("RSF", $no_ligne, "Participation assuré avant OC", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["total_assure_avant_oc_offset"], $BUF_offsets["total_assure_avant_oc_len"]);
                                }
                                
                                // patient bénéficiaire de la CMU (L'absence de valeur n'est pas une erreur
                                $value = $BUF_record["pat_benef_cmu"];
                                if ($value != "0" && $value != "1" && $value != "O" && $value != "N" && $value != "") {
                                    $erreur = "Valeur $value incorrecte";
                                    $commentaire = "Aucune valeur ne sera remontée";
                                    controle_add_error("RSF", $no_ligne, "Patient bénéficaire de la CMU", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["pat_benef_cmu_offset"], $BUF_offsets["pat_benef_cmu_len"]);
                                }
                                
                                if ($ENV_TYPEETS == "2" || $ENV_TYPEETS == "3") {   // RSF-ACE
                                    $value = $BUF_record["valorise_fides"];
                                    if ($value != "0" && $value != "1" && $value != "O" && $value != "N" && $value != "") {
                                        $erreur = "Valeur $value incorrecte";
                                        $commentaire = "Aucune valeur ne sera remontée";
                                        controle_add_error("RSF", $no_ligne, "valorisé par FIDES", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["valorise_fides_offset"], $BUF_offsets["valorise_fides_len"]);
                                    }
                                }

                            }
                        
                        }
                        
                        // RSF B
                        if ($BUF_record["type_enregistrement"] == "B" && $rss_ok == TRUE) {

                            // Finess
                            if (1 == 2) {
                            if ($BUF_record["finess"] != $ENV_FINESS && $finess_error == FALSE) {
                                $erreur = "Valeur " . $BUF_record["finess"] . " différente de $ENV_FINESS";
                                $commentaire = "Le fichier est erroné";
                                controle_add_error("RSF", $no_ligne, "Finess", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["finess_offset"], $BUF_offsets["finess_len"]);
                                $finess_error = TRUE;
                            }
                            }
                            
                            
                            // RSS
                            if (! controle_check_num($BUF_record["no_rss"],0,FALSE,$erreur,$commentaire)) {
                                $commentaire = "";
                                controle_add_error("RSF", $no_ligne, "Numéro RSS", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["no_rss_offset"], $BUF_offsets["no_rss_len"]);
                            }
                            else {
                                if ($file_exists_RSS) {
                                    if ($BUF_record["code_acte"] == 'GHS') {
                                        $no_rss = get_numrss($BUF_record["no_rss"]);
                                        $in_rsf = "";
                                        $in_rsf = @$rsss_array[$no_rss];
                                        if ($in_rsf != "OK") {
                                            $erreur = "Aucun RUM pour le RSS " . $BUF_record["no_rss"] ;
                                            $commentaire = "";
                                            controle_add_error("RSF", $no_ligne, "Numéro RSS", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["no_rss_offset"], $BUF_offsets["no_rss_len"]);
                                        }
                                    }
                                }
                            }
                            
                            // MT
                            if (! controle_check_num($BUF_record["mode_traitement"],2, TRUE,$erreur,$commentaire)) {
                                $commentaire = "Blanc pris par défaut";
                                controle_add_error("RSF", $no_ligne, "Mode traitement", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["mode_traitement_offset"], $BUF_offsets["mode_traitement_len"]);
                            }
                            
                            // DMT
                            if (! controle_check_num($BUF_record["discpline_prestation"],3, TRUE,$erreur,$commentaire)) {
                                $commentaire = "Blanc pris par défaut";
                                controle_add_error("RSF", $no_ligne, "discipline prestation", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["discpline_prestation_offset"], $BUF_offsets["discpline_prestation_len"]);
                            }
                            
                            // Date début
                            if (! controle_check_date($BUF_record["date_debut"],$erreur,$commentaire)) {
                                $commentaire = "";
                                controle_add_error("RSF", $no_ligne, "Date début", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["date_debut_offset"], $BUF_offsets["date_debut_len"]);
                            }
                            
                            
                            // Date fin
                            if (! controle_check_date($BUF_record["date_fin"],$erreur,$commentaire)) {
                                $commentaire = "";
                                controle_add_error("RSF", $no_ligne, "Date fin", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["date_fin_offset"], $BUF_offsets["date_fin_len"]);
                            }
                            
                            // acte
                            if (! check_prestation($BUF_record["code_acte"], $gravite, $erreur, $commentaire)) {
                                controle_add_error("RSF", $no_ligne, "Code acte", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["code_acte_offset"], $BUF_offsets["code_acte_len"]);
                            }
                                
                            // nombre
                            if (! controle_check_num($BUF_record["nombre"],3, FALSE,$erreur,$commentaire)) {
                                $commentaire = "1 pris par défaut";
                                controle_add_error("RSF", $no_ligne, "Quantité", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["nombre_offset"], $BUF_offsets["nombre_len"]);
                            }
                            
                            // coefficient
                            if (! controle_check_num($BUF_record["coefficient"],0, FALSE,$erreur,$commentaire)) {
                                $commentaire = "1 pris par défaut";
                                controle_add_error("RSF", $no_ligne, "Coefficient", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["coefficient_offset"], $BUF_offsets["coefficient_len"]);
                            }
                            
                            // prix unitaire
                            if (! controle_check_num($BUF_record["prix_unitaire"],7, FALSE,$erreur,$commentaire)) {
                                $commentaire = "0 pris par défaut";
                                controle_add_error("RSF", $no_ligne, "Prix unitaire", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["prix_unitaire_offset"], $BUF_offsets["prix_unitaire_len"]);
                            }
                            
                            // base remboursement
                            if (! controle_check_num($BUF_record["base_remboursement"],8, FALSE,$erreur,$commentaire)) {
                                $commentaire = "0 pris par défaut";
                                controle_add_error("RSF", $no_ligne, "Base remboursement", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["base_remboursement_offset"], $BUF_offsets["base_remboursement_len"]);
                            }
                            
                            // coefficient mco
                            if (! controle_check_num($BUF_record["coefficient_mco"],5, FALSE,$erreur,$commentaire)) {
                                $commentaire = "1 pris par défaut";
                                controle_add_error("RSF", $no_ligne, "Coefficient mco", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["coefficient_mco_offset"], $BUF_offsets["coefficient_mco_len"]);
                            }
                            
                            // taux remboursement
                            if (! controle_check_num($BUF_record["taux"],3, FALSE,$erreur,$commentaire)) {
                                $commentaire = "100 pris par défaut";
                                controle_add_error("RSF", $no_ligne, "Taux remboursement", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["taux_offset"], $BUF_offsets["taux_len"]);
                            }
                            
                            // sejour facture
                            if (! controle_check_num($BUF_record["montant_total_depense"],8, FALSE,$erreur,$commentaire)) {
                                $commentaire = "0 pris par défaut";
                                controle_add_error("RSF", $no_ligne, "Montant facturé", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["montant_total_depense_offset"], $BUF_offsets["montant_total_depense_len"]);
                            }
                            
                            // Montant remboursable
                            if (! controle_check_num($BUF_record["montant_remboursable"],8, FALSE,$erreur,$commentaire)) {
                                $commentaire = "0 pris par défaut";
                                controle_add_error("RSF", $no_ligne, "Montant remboursable", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["montant_remboursable_offset"], $BUF_offsets["montant_remboursable_len"]);
                            }
                            
                            // ghs
                            $ghsError = FALSE;
                            if ($BUF_record["code_acte"] == "GHS" || $BUF_record["code_acte"] == "EXH" || $BUF_record["no_ghs"] != "") {
                                if (! check_ghs($BUF_record["no_ghs"], $gravite, $erreur, $commentaire)) {
                                    controle_add_error("RSF", $no_ligne, "Code GHS", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["no_ghs_offset"], $BUF_offsets["no_ghs_len"]);
                                }
                            }
                            
                            
                            // Montant remboursé noemie
                            if (! controle_check_num($BUF_record["montant_remboursé_noemie"],8, FALSE,$erreur,$commentaire)) {
                                $commentaire = "0 pris par défaut";
                                controle_add_error("RSF", $no_ligne, "Montant remboursé NOEMIE", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["montant_remboursé_noemie_offset"], $BUF_offsets["montant_remboursé_noemie_len"]);
                            }
                            
                            // Type RSS
                            if ($BUF_record["code_acte"] == 'GHS') {
                                $type_rss = "GHS";
                            }
                            if ($type_rss == "") {
                                if ($BUF_record["code_acte"] == 'SE1') {
                                    $type_rss = "SE1";
                                }
                                if ($BUF_record["code_acte"] == 'SE2') {
                                    $type_rss = "SE2";
                                }
                                if ($BUF_record["code_acte"] == 'SE3') {
                                    $type_rss = "SE3";
                                }
                                if ($BUF_record["code_acte"] == 'SE4') {
                                    $type_rss = "SE4";
                                }
                                if ($BUF_record["code_acte"] == 'SE5') {
                                    $type_rss = "SE5";
                                }
                                if ($BUF_record["code_acte"] == 'SE6') {
                                    $type_rss = "SE6";
                                }
								if ($BUF_record["code_acte"] == 'SE7') {
                                    $type_rss = "SE7";
                                } 								
                                if ($BUF_record["code_acte"] == 'FFM') {
                                    $type_rss = "FFM";
                                }
                                if ($BUF_record["code_acte"] == 'ATU') {
                                    $type_rss = "ATU";
                                }
                                if ($BUF_record["code_acte"] == 'APE') {
                                    $type_rss = "APE";
                                }   
                                if ($BUF_record["code_acte"] == 'AP2') {
                                    $type_rss = "AP2";
                                }    
                                if ($BUF_record["code_acte"] == 'FPI') {
                                    $type_rss = "FPI";
                                }                                          
                            }


                        }
                        
                        // RSF C
                        if ($BUF_record["type_enregistrement"] == "C" && $rss_ok == TRUE) {

                            // Finess
                            if (1 == 2) {
                            if ($BUF_record["finess"] != $ENV_FINESS && $finess_error == FALSE) {
                                $erreur = "Valeur " . $BUF_record["finess"] . " différente de $ENV_FINESS";
                                $commentaire = "Le fichier est erroné";
                                controle_add_error("RSF", $no_ligne, "Finess", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["finess_offset"], $BUF_offsets["finess_len"]);
                                $finess_error = TRUE;
                            }
                            }
                            
                            
                            // RSS
                            if (! controle_check_num($BUF_record["no_rss"],0,FALSE,$erreur,$commentaire)) {
                                $commentaire = "";
                                controle_add_error("RSF", $no_ligne, "Numéro RSS", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["no_rss_offset"], $BUF_offsets["no_rss_len"]);
                            }
                            
                            
                            // MT
                            if (! controle_check_num($BUF_record["mode_traitement"],2, TRUE,$erreur,$commentaire)) {
                                $commentaire = "Blanc pris par défaut";
                                controle_add_error("RSF", $no_ligne, "Mode traitement", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["mode_traitement_offset"], $BUF_offsets["mode_traitement_len"]);
                            }
                            
                            // DMT
                            if (! controle_check_num($BUF_record["discpline_prestation"],3, TRUE,$erreur,$commentaire)) {
                                $commentaire = "Blanc pris par défaut";
                                controle_add_error("RSF", $no_ligne, "discipline prestation", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["discpline_prestation_offset"], $BUF_offsets["discpline_prestation_len"]);
                            }
                            
                            // Date début
                            if (! controle_check_date($BUF_record["date_debut"],$erreur,$commentaire)) {
                                $commentaire = "";
                                controle_add_error("RSF", $no_ligne, "Date début", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["date_debut_offset"], $BUF_offsets["date_debut_len"]);
                            }
                            
                            
                            // Date fin
                            if (! controle_check_date($BUF_record["date_fin"],$erreur,$commentaire)) {
                                $commentaire = "";
                                controle_add_error("RSF", $no_ligne, "Date fin", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["date_fin_offset"], $BUF_offsets["date_fin_len"]);
                            }                     

                                // acte
                                if (! check_prestation($BUF_record["code_acte"], $gravite, $erreur, $commentaire)) {
                                    controle_add_error("RSF", $no_ligne, "Code acte", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["code_acte_offset"], $BUF_offsets["code_acte_len"]);
                            }
                                
                            // nombre
                            if (! controle_check_num($BUF_record["nombre"],3, FALSE,$erreur,$commentaire)) {
                                $commentaire = "1 pris par défaut";
                                controle_add_error("RSF", $no_ligne, "Quantité", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["nombre_offset"], $BUF_offsets["nombre_len"]);
                            }
                            
                            // coefficient
                            if (! controle_check_num($BUF_record["coefficient"],0, FALSE,$erreur,$commentaire)) {
                                $commentaire = "1 pris par défaut";
                                controle_add_error("RSF", $no_ligne, "Coefficient", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["coefficient_offset"], $BUF_offsets["coefficient_len"]);
                            }
                            
                            // prix unitaire
                            if (! controle_check_num($BUF_record["prix_unitaire"],7, FALSE,$erreur,$commentaire)) {
                                $commentaire = "0 pris par défaut";
                                controle_add_error("RSF", $no_ligne, "Prix unitaire", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["prix_unitaire_offset"], $BUF_offsets["prix_unitaire_len"]);
                            }
                            
                            // base remboursement
                            if (! controle_check_num($BUF_record["base_remboursement"],8, FALSE,$erreur,$commentaire)) {
                                $commentaire = "0 pris par défaut";
                                controle_add_error("RSF", $no_ligne, "Base remboursement", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["base_remboursement_offset"], $BUF_offsets["base_remboursement_len"]);
                            }
                            
                            // coefficient mco
                            if (! controle_check_num($BUF_record["coefficient_mco"],5, FALSE,$erreur,$commentaire)) {
                                $commentaire = "1 pris par défaut";
                                controle_add_error("RSF", $no_ligne, "Coefficient mco", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["coefficient_mco_offset"], $BUF_offsets["coefficient_mco_len"]);
                            }
                            
                            // taux remboursement
                            if (! controle_check_num($BUF_record["taux"],3, FALSE,$erreur,$commentaire)) {
                                $commentaire = "100 pris par défaut";
                                controle_add_error("RSF", $no_ligne, "Taux remboursement", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["taux_offset"], $BUF_offsets["taux_len"]);
                            }
                            
                            // sejour facture
                            if (! controle_check_num($BUF_record["montant_total_depense"],8, FALSE,$erreur,$commentaire)) {
                                $commentaire = "0 pris par défaut";
                                controle_add_error("RSF", $no_ligne, "Montant facturé", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["montant_total_depense_offset"], $BUF_offsets["montant_total_depense_len"]);
                            }
                            
                            // Montant remboursable
                            if (! controle_check_num($BUF_record["montant_remboursable"],8, FALSE,$erreur,$commentaire)) {
                                $commentaire = "0 pris par défaut";
                                controle_add_error("RSF", $no_ligne, "Montant remboursable", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["montant_remboursable_offset"], $BUF_offsets["montant_remboursable_len"]);
                            }
                            

                        }
                        
                        // RSF P (LPP)
                        if ($BUF_record["type_enregistrement"] == "P"  && $rss_ok == TRUE) {
                        
                            // Finess
                            if (1 == 2) {
                            if ($BUF_record["finess"] != $ENV_FINESS && $finess_error == FALSE) {
                                $erreur = "Valeur " . $BUF_record["finess"] . " différente de $ENV_FINESS";
                                $commentaire = "Le fichier est erroné";
                                controle_add_error("RSF", $no_ligne, "Finess", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["finess_offset"], $BUF_offsets["finess_len"]);
                                $finess_error = TRUE;
                            }
                            }
                            
                            
                            // RSS
                            if (! controle_check_num($BUF_record["no_rss"],0,FALSE,$erreur,$commentaire)) {
                                $commentaire = "";
                                controle_add_error("RSF", $no_ligne, "Numéro RSS", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["no_rss_offset"], $BUF_offsets["no_rss_len"]);
                            }
                            
                            
                            // Date début
                            if (! controle_check_date($BUF_record["date_debut"],$erreur,$commentaire)) {
                                $commentaire = "";
                                controle_add_error("RSF", $no_ligne, "Date début", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["date_debut_offset"], $BUF_offsets["date_debut_len"]);
                            }
                            
                            
                            
                            
                            // code LPP
                            if (! check_lpp($BUF_record["code_lpp"], $gravite, $erreur, $commentaire)) {
                                controle_add_error("RSF", $no_ligne, "Code LPP", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["code_lpp_offset"], $BUF_offsets["code_lpp_len"]);
                            }
                                
                            // nombre
                            if (! controle_check_num($BUF_record["nombre"],2, FALSE,$erreur,$commentaire)) {
                                $commentaire = "1 pris par défaut";
                                controle_add_error("RSF", $no_ligne, "Quantité", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["nombre_offset"], $BUF_offsets["nombre_len"]);
                            }
                            
                            // prix unitaire
                            if (! controle_check_num($BUF_record["prix_unitaire"],7, FALSE,$erreur,$commentaire)) {
                                $commentaire = "0 pris par défaut";
                                controle_add_error("RSF", $no_ligne, "Prix unitaire", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["prix_unitaire_offset"], $BUF_offsets["prix_unitaire_len"]);
                            }
                            
                            // montant_facture
                            if (! controle_check_num($BUF_record["montant_facture"],7, FALSE,$erreur,$commentaire)) {
                                $commentaire = "0 pris par défaut";
                                controle_add_error("RSF", $no_ligne, "Montant facturé", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["montant_facture_offset"], $BUF_offsets["montant_facture_len"]);
                            }
                            
                            
                            
                            if (get_num($BUF_record["nombre_2"]) > 0) {
                            
                                // code LPP
                                if (! check_lpp($BUF_record["code_lpp_2"], $gravite, $erreur, $commentaire)) {
                                    controle_add_error("RSF", $no_ligne, "Code LPP (2)", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["code_lpp_2_offset"], $BUF_offsets["code_lpp_2_len"]);
                                }
                                    
                                // nombre
                                if (! controle_check_num($BUF_record["nombre_2"],2, FALSE,$erreur,$commentaire)) {
                                    $commentaire = "1 pris par défaut";
                                    controle_add_error("RSF", $no_ligne, "Quantité (2)", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["nombre_2_offset"], $BUF_offsets["nombre_2_len"]);
                                }
                                
                                // prix unitaire
                                if (! controle_check_num($BUF_record["prix_unitaire_2"],7, FALSE,$erreur,$commentaire)) {
                                    $commentaire = "0 pris par défaut";
                                    controle_add_error("RSF", $no_ligne, "Prix unitaire (2)", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["prix_unitaire_2_offset"], $BUF_offsets["prix_unitaire_2_len"]);
                                }
                                
                                // montant_facture
                                if (! controle_check_num($BUF_record["montant_facture_2"],7, FALSE,$erreur,$commentaire)) {
                                    $commentaire = "0 pris par défaut";
                                    controle_add_error("RSF", $no_ligne, "Montant facturé (2)", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["montant_facture_2_offset"], $BUF_offsets["montant_facture_2_len"]);
                                }
                            
                            }


                        }
                        
                        // RSF H (LUCD)
                        if ($BUF_record["type_enregistrement"] == "H"  && $rss_ok == TRUE) {
                        
                            // Finess
                            if (1 == 2) {
                            if ($BUF_record["finess"] != $ENV_FINESS && $finess_error == FALSE) {
                                $erreur = "Valeur " . $BUF_record["finess"] . " différente de $ENV_FINESS";
                                $commentaire = "Le fichier est erroné";
                                controle_add_error("RSF", $no_ligne, "Finess", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["finess_offset"], $BUF_offsets["finess_len"]);
                                $finess_error = TRUE;
                            }
                            }
                            
                            
                            // RSS
                            if (! controle_check_num($BUF_record["no_rss"],0,FALSE,$erreur,$commentaire)) {
                                $commentaire = "";
                                controle_add_error("RSF", $no_ligne, "Numéro RSS", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["no_rss_offset"], $BUF_offsets["no_rss_len"]);
                            }
                            
                            
                            // Date début
                            if (! controle_check_date($BUF_record["date_debut"],$erreur,$commentaire)) {
                                $commentaire = "";
                                controle_add_error("RSF", $no_ligne, "Date début", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["date_debut_offset"], $BUF_offsets["date_debut_len"]);
                            }
                            
                            
                            
                            
                            // code UCD
                            if (! check_ucd($BUF_record["code_ucd"], $gravite, $erreur, $commentaire)) {
                                controle_add_error("RSF", $no_ligne, "Code UCD", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["code_ucd_offset"], $BUF_offsets["code_ucd_len"]);
                            }
                                
                            // nombre
                            if (! controle_check_num($BUF_record["nombre"],3, FALSE,$erreur,$commentaire)) {
                                $commentaire = "1 pris par défaut";
                                controle_add_error("RSF", $no_ligne, "Quantité", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["nombre_offset"], $BUF_offsets["nombre_len"]);
                            }
                            
                            // prix unitaire achat
                            if (! controle_check_num($BUF_record["prix_unitaire_achat"],7, FALSE,$erreur,$commentaire)) {
                                $commentaire = "0 pris par défaut";
                                controle_add_error("RSF", $no_ligne, "Prix unitaire achat", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["prix_unitaire_achat_offset"], $BUF_offsets["prix_unitaire_len"]);
                            }
                            
                            // montant_facture
                            if (! controle_check_num($BUF_record["montant_facture"],7, FALSE,$erreur,$commentaire)) {
                                $commentaire = "0 pris par défaut";
                                controle_add_error("RSF", $no_ligne, "Montant facturé", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["montant_facture_offset"], $BUF_offsets["montant_facture_len"]);
                            }
                            

                        }
                        
                        // RSF M actes
                        if ($BUF_record["type_enregistrement"] == "M"  && $rss_ok == TRUE) {
                        
                            // Finess
                            if (1 == 2) {
                            if ($BUF_record["finess"] != $ENV_FINESS && $finess_error == FALSE) {
                                $erreur = "Valeur " . $BUF_record["finess"] . " différente de $ENV_FINESS";
                                $commentaire = "Le fichier est erroné";
                                controle_add_error("RSF", $no_ligne, "Finess", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["finess_offset"], $BUF_offsets["finess_len"]);
                                $finess_error = TRUE;
                            }
                            }
                            
                            
                            // RSS
                            if (! controle_check_num($BUF_record["no_rss"],0,FALSE,$erreur,$commentaire)) {
                                $commentaire = "";
                                controle_add_error("RSF", $no_ligne, "Numéro RSS", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["no_rss_offset"], $BUF_offsets["no_rss_len"]);
                            }
                            
                            // MT
                            if (! controle_check_num($BUF_record["mode_traitement"],2, TRUE,$erreur,$commentaire)) {
                                $commentaire = "Blanc pris par défaut";
                                controle_add_error("RSF", $no_ligne, "Mode traitement", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["mode_traitement_offset"], $BUF_offsets["mode_traitement_len"]);
                            }
                            
                            // DMT
                            if (! controle_check_num($BUF_record["discpline_prestation"],3, TRUE,$erreur,$commentaire)) {
                                $commentaire = "Blanc pris par défaut";
                                controle_add_error("RSF", $no_ligne, "discipline prestation", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["discpline_prestation_offset"], $BUF_offsets["discpline_prestation_len"]);
                            }
                            
                            
                            // Date acte
                            if (! controle_check_date($BUF_record["date_acte"],$erreur,$commentaire)) {
                                $commentaire = "";
                                controle_add_error("RSF", $no_ligne, "Date acte", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["date_acte_offset"], $BUF_offsets["date_acte_len"]);
                            }
                                                    
                            // code CCAM
                            if (! check_acte($BUF_record["code_acte"], $gravite, $erreur, $commentaire)) {
                                controle_add_error("RSF", $no_ligne, "Code acte CCAM", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["code_acte_offset"], $BUF_offsets["code_acte_len"]);
                            }
                                
                            // activite
                            if (! controle_check_num($BUF_record["activite_ccam"],1, FALSE,$erreur,$commentaire)) {
                                $commentaire = "";
                                controle_add_error("RSF", $no_ligne, "Activité CCAM", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["activite_ccam_offset"], $BUF_offsets["activite_ccam_len"]);
                            }
                            
                            // phase
                            if (! controle_check_num($BUF_record["phase_ccam"],1, FALSE,$erreur,$commentaire)) {
                                $commentaire = "";
                                controle_add_error("RSF", $no_ligne, "Phase CCAM", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["phase_ccam_offset"], $BUF_offsets["phase_ccam_len"]);
                            }
                            
                            // Medecin acte
                            if ($file_exists_ACTMED) {
                                $cle = get_numrss($BUF_record["no_rss"]);
                                $cle = $cle . $BUF_record["code_acte"];
                                $cle = $cle . get_date_AAAAMMJJ($BUF_record["date_acte"]);
                                $cle = $cle . $BUF_record["activite_ccam"];
                                $code_med = "";
                                $code_med = $actmed_array[$cle];
                                if ($code_med == "") {
                                    $cle = get_numrss($BUF_record["no_rss"]);
                                    $cle = $cle . $BUF_record["code_acte"];
                                    $cle = $cle . "00000000";
                                    $cle = $cle . $BUF_record["activite_ccam"];
                                    $code_med = "";
                                    $code_med = $actmed_array[$cle];
                                }
                                if ($code_med == "") {
                                    if ($type_rss != "SE1" && $type_rss != "SE2" && $type_rss != "SE3" && $type_rss != "SE4" && $type_rss != "SE5" && $type_rss != "SE6" && $type_rss != "SE7" && $type_rss != "FFM" && $type_rss != "ATU" && $type_rss != "APE" && $type_rss != "AP2" && $type_rss != "FPI") {
                                        //$erreur = "Association Acte-Exécutant inexistante pour RSS " . $type_rss . " " . $BUF_record["no_rss"] . " acte " . $BUF_offsets["code_acte"] . "-" . $BUF_offsets["activite_ccam"];
                                        //$commentaire = "Blanc pris par défaut";
                                        //controle_add_error("RSF", $no_ligne, "Code acte CCAM", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["code_acte_offset"], $BUF_offsets["code_acte_len"]);
                                    }
                                }
                            
                            }
                            
                            
                        }
						
						// RSF I
                        if ($BUF_record["type_enregistrement"] == "I" && $rss_ok == TRUE) {

                            // Finess
                            if (1 == 2) {
                            if ($BUF_record["finess"] != $ENV_FINESS && $finess_error == FALSE) {
                                $erreur = "Valeur " . $BUF_record["finess"] . " différente de $ENV_FINESS";
                                $commentaire = "Le fichier est erroné";
                                controle_add_error("RSF", $no_ligne, "Finess", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["finess_offset"], $BUF_offsets["finess_len"]);
                                $finess_error = TRUE;
                            }
                            }
                            
                            
                            // RSS
                            if (! controle_check_num($BUF_record["no_rss"],0,FALSE,$erreur,$commentaire)) {
                                $commentaire = "";
                                controle_add_error("RSF", $no_ligne, "Numéro RSS", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["no_rss_offset"], $BUF_offsets["no_rss_len"]);
                            }
                            
                            
                            // Date début
                            if (! controle_check_date($BUF_record["date_debut"],$erreur,$commentaire)) {
                                $commentaire = "";
                                controle_add_error("RSF", $no_ligne, "Date début", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["date_debut_offset"], $BUF_offsets["date_debut_len"]);
                            }
                            
                            
                            // Date fin
                            if (! controle_check_date($BUF_record["date_fin"],$erreur,$commentaire)) {
                                $commentaire = "";
                                controle_add_error("RSF", $no_ligne, "Date fin", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["date_fin_offset"], $BUF_offsets["date_fin_len"]);
                            }
                            
							// Finess destination
							if (! controle_check_num($BUF_record["finess_dest"],0,FALSE,$erreur,$commentaire)) {
                                $commentaire = "";
                                controle_add_error("RSF", $no_ligne, "Finess destination", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["finess_dest_offset"], $BUF_offsets["finess_len"]);
                                $finess_error = TRUE;
                            }
                        }
                        
                    }
                }
            
            }
            
            fclose($handle);
        
        }
    
    }
    
    else {
        controle_add_error("FILE", 0, "", "", "Fichier des RSF absent", 4, "", $nbI, $nbW, $nbE);

    }
    
    
    

    $sqlcmd = "UPDATE pmsi.p_imports SET ";
    $sqlcmd = $sqlcmd . "nb_rsf = $nb_rsf,  ";
    $sqlcmd = $sqlcmd . "nb_erreurs = nb_erreurs + $nbE, nb_avertissements = nb_avertissements + $nbW ";
    $sqlcmd = $sqlcmd . "WHERE oid = $import_id";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    
    
    commit_trans();

    logInfoMsg("FIN CONTROLE DES RSF. $nb lus, $nbI informations, $nbW avertissements, $nbE erreurs graves");
    
}

function controle_fichsup() {

    global $file_TSP;
    global $file_exists_TSP;
    global $import_id;
    
    logInfoMsg("CONTROLE DE FICHSUP");
    
    $nb = 0;
    $nbI = 0;
    $nbW = 0;
    $nbE = 0;
    $no_ligne = 0;
    $nb_tsp = 0;
    
    begin_trans();
    
    if ($file_exists_TSP) {
        $handle = fopen($file_TSP, "r");
        if ($handle) {
            while (!feof($handle)) {
                $buffer = fgets($handle, 99999);
                $no_ligne++;
                if (trim($buffer) != "" && $no_ligne < 1000000 ) {
                
                    $nb++;
                    $BUF_record = read_tsp_line($buffer);
                    
                    if ($BUF_record["ok"] === TRUE && $BUF_record["type_fichier"] == "G61") {
                        
                        $BUF_offsets = $BUF_record["BUF_offsets"];
                        $nb_tsp++;
                        if (! check_prestation($BUF_record["code"], $gravite, $erreur, $commentaire)) {
                            controle_add_error("TSP", $no_ligne, "Code acte", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["code_offset"], $BUF_offsets["code_len"]);
                        }
                    }
                }
            }
            fclose($handle);
        }
    }
    else {
        controle_add_error("FILE", 0, "", "", "Fichier FICHSUP transports absent", 1, "", $nbI, $nbW, $nbE);
    }
    
    if ($nbE > 0 || $nbW > 0) {
        
        $sqlcmd = "
            UPDATE pmsi.p_imports SET
                nb_erreurs = nb_erreurs + $nbE, 
                nb_avertissements = nb_avertissements + $nbW
            WHERE oid = $import_id";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW);
    }
    
    commit_trans();
    
    logInfoMsg("FIN CONTROLE CONTROLE DE FICHSUP. $nb lus, $nbI informations, $nbW avertissements, $nbE erreurs graves");
}

function controle_fichcomp() {

    
    global $import_id;

    global $file_RSS;
    global $file_FCP;

    global $file_exists_RSS;
    global $file_exists_FCP;

    
    $rssadms_array = array();
    
    logInfoMsg("CONTROLE DE FICHCOMP");

    $nb = 0;
    $nbI = 0;
    $nbW = 0;
    $nbE = 0;
    $no_ligne = 0;
    
    if ($file_exists_RSS) {
        $handle = @fopen($file_RSS, "r");
        if ($handle) {
            while (!feof($handle)) {
                $buffer = fgets($handle, 99999);
                
                $no_ligne++;
                if (trim($buffer) != "" && $no_ligne < 100000000000) {
                
                    $nb++;
                    
                    $BUF_record = read_rum_partial_line($buffer);
                    
                    if ($BUF_record["type_enregistrement"] == "RUM") {

                        if (controle_check_num($BUF_record["no_sejour_administratif"],0,FALSE,$erreur,$commentaire)) {
                            $no_rss = get_numrss($BUF_record["no_rss"]);
                            $no_sejour_administratif = get_charAsNum($BUF_record["no_sejour_administratif"]);
                            $rssadms_array[$no_sejour_administratif] = $no_rss;
                        }
                        
                    }
                    
                }
                
            }
            
        }
    }
    
    begin_trans();

    
    $no_ligne = 0;
    
    $nb_fcp = 0;
    
    if ($file_exists_FCP) {
        $handle = @fopen($file_FCP, "r");
        if ($handle) {
            while (!feof($handle)) {
                $buffer = fgets($handle, 99999);
                
                $no_ligne++;
                if (trim($buffer) != "" && $no_ligne < 100000000000 ) {
                
                    $nb++;
                    
                    $BUF_record = read_fcp_line($buffer);
                    
                    
                    if ($BUF_record["ok"] == TRUE) {
                    
                        $nb_fcp++;
                        
                        $BUF_offsets = $BUF_record["BUF_offsets"];
                        // Controle si ligne acceptée par GENRSA
                        if (! check_complog_fichcomp($buffer, $gravite, $erreur, $commentaire)) {
                            controle_add_error("FCP", $no_ligne, "Format", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["no_sejour_administratif_offset"], $BUF_offsets["no_sejour_administratif_len"]);
                        }
                        else {
                            // Autres controles
                            if (! controle_check_num($BUF_record["no_rum"],0,TRUE,$erreur,$commentaire)) {
                                $commentaire = "";
                                controle_add_error("FCP", $no_ligne, "Numéro RUM", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["no_rum_offset"], $BUF_offsets["no_rum_len"]);
                            }
        
                            if (! controle_check_date($BUF_record["date_debut"],$erreur,$commentaire)) {
                                $commentaire = "";
                                controle_add_error("FCP", $no_ligne, "Date debut", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["date_debut_offset"], $BUF_offsets["date_debut_len"]);
                            }
                            else {
                                if (! controle_check_date($BUF_record["date_fin"],$erreur,$commentaire)) {
                                    $commentaire = "";
                                    controle_add_error("FCP", $no_ligne, "Date fin", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["date_fin_offset"], $BUF_offsets["date_fin_len"]);
                                }
                            }
                            
                            if (! controle_check_num($BUF_record["no_sejour_administratif"],0,FALSE,$erreur,$commentaire)) {
                                $commentaire = "";
                                controle_add_error("FCP", $no_ligne, "N° Séjour", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["no_sejour_administratif_offset"], $BUF_offsets["no_sejour_administratif_len"]);
                            }
                            else {
                                $no_sejour_administratif = get_charAsNum($BUF_record["no_sejour_administratif"]);
                                $no_rss = @$rssadms_array[$no_sejour_administratif];
                                if (get_numrss($no_rss) == 0) {
                                    $erreur = "Pas de RSS trouvé pour le séjour " . $BUF_record["no_sejour_administratif"];
                                    $commentaire = "";
                                    controle_add_error("FCP", $no_ligne, "N° Séjour", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["no_sejour_administratif_offset"], $BUF_offsets["no_sejour_administratif_len"]);
                                }
                            }
                            
                            if (! controle_check_num($BUF_record["nombre"],0,FALSE,$erreur,$commentaire)) {
                                $commentaire = "";
                                controle_add_error("FCP", $no_ligne, "Nombre", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["nombre_offset"], $BUF_offsets["nombre_len"]);
                            }
                            
                            if (! controle_check_num($BUF_record["montant_paye"],0,FALSE,$erreur,$commentaire)) {
                                $commentaire = "";
                                controle_add_error("FCP", $no_ligne, "Montant payé", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["montant_paye_offset"], $BUF_offsets["montant_paye_len"]);
                            }
                            
                            if ($BUF_record["type_enregistrement"] == "01"|| $BUF_record["type_enregistrement"] == "06" || $BUF_record["type_enregistrement"] == "09") {
                                if (! check_ucd($BUF_record["code"], $gravite, $erreur, $commentaire)) {
                                    controle_add_error("FCP", $no_ligne, "Code UCD" , $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["code_ucd_offset"], $BUF_offsets["code_ucd_len"]);
                                }
                            }
                            
                            if ($BUF_record["type_enregistrement"] == "02") {
                                if (! check_lpp($BUF_record["code"], $gravite, $erreur, $commentaire)) {
                                    controle_add_error("FCP", $no_ligne, "Code LPP" , $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["code_lpp_offset"], $BUF_offsets["code_lpp_len"]);
                                }
                            }
                        
                        }
                    
                    }

                }
            
            }
            
            fclose($handle);
        
        }
        
    }
    else {
        controle_add_error("FILE", 0, "", "", "Fichier FICHCOMP absent", 1, "", $nbI, $nbW, $nbE);
    
    }
    
    if ($nbE > 0 || $nbW > 0) {

        $sqlcmd = "UPDATE pmsi.p_imports SET ";
        $sqlcmd = $sqlcmd . "nb_erreurs = nb_erreurs + $nbE, nb_avertissements = nb_avertissements + $nbW ";
        $sqlcmd = $sqlcmd . "WHERE oid = $import_id";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );

    }
    
    commit_trans();
    
    logInfoMsg("FIN CONTROLE CONTROLE DE FICHCOMP. $nb lus, $nbI informations, $nbW avertissements, $nbE erreurs graves");
   
}

/**
 * Controle du fichier ano dans les OUT
 * Correspond au vidhosp anonymisé
 */
function controle_ano_vidhosp() {

    global $import_id;

    global $file_ANO;
    global $file_RSA;

    global $file_exists_RSA;
    global $file_exists_ANO;

    $rsas_array = array();
    
    logInfoMsg("CONTROLE DE ANO (VIDHOSP OUT)");

    $nb = 0;
    $nbI = 0;
    $nbW = 0;
    $nbE = 0;
    
    begin_trans();

    $nb_vidhosp = 0;

    if (!$file_exists_ANO) {
        controle_add_error("FILE", 0, "", "", "Fichier ANO (VIDHOSP OUT) absent, génératon ANO impossible", 1, "", $nbI, $nbW, $nbE);
    }

    if (!$file_exists_RSA) {
        controle_add_error("FILE", 0, "", "", "Fichier RSA absent (pour ANO), génératon ANO impossible", 1, "", $nbI, $nbW, $nbE);
    }

    if ($file_exists_ANO && $file_exists_RSA) {

        $handle = @fopen($file_RSA, "r");
        if ($handle) {
            $no_ligne = 0;
            while (!feof($handle)) {
                $buffer = fgets($handle, 99999);

                $no_ligne++;
                if (trim($buffer) !== "" && $no_ligne < 100000000000) {

                    $nb++;

                    $BUF_record = read_rsa_line($buffer);

                    if ($BUF_record["type_enregistrement"] === "RSA") {

                        if (controle_check_num($BUF_record["no_rsa"],0,false,$erreur,$commentaire)) {
                            $no_rsa = get_num($BUF_record["no_rsa"]);
                            $rsas_array[$no_rsa] = $no_rsa;
                        }

                    }

                }

            }

        }
        fclose($handle);


        $handle = @fopen($file_ANO, "r");
        if ($handle) {
            $no_ligne = 0;
            while (!feof($handle)) {
                $buffer = fgets($handle, 99999);

                $no_ligne++;
                if (trim($buffer) !== "" && $no_ligne < 100000000000 ) {

                    $nb++;

                    $BUF_record = read_ano_line($buffer);

                    $BUF_offsets = $BUF_record["BUF_offsets"];


                    if ($BUF_record["ok"] === true) {

                        $nb_vidhosp++;

                        if ($BUF_record["type_enregistrement"] === "ANO") {

                            if (! controle_check_num($BUF_record["no_rsa"],0,false,$erreur,$commentaire)) {
                                $commentaire = "";
                                controle_add_error("VID", $no_ligne, "N° RSA", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["no_rsa_offset"], $BUF_offsets["no_rsa_len"]);
                            }
                            else {
                                $no_rsa = get_num($BUF_record["no_rsa"]);
                                $no_rsax = @$rsas_array[$no_rsa];
                                if (get_num($no_rsax) == 0) {
                                    $erreur = "Pas de RSA trouvé pour le n° " . $BUF_record["no_rsa"];
                                    $commentaire = "";
                                    controle_add_error("VID", $no_ligne, "N° RSA", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["no_rsa_offset"], $BUF_offsets["no_rsa_len"]);
                                }
                            }

                            $value = $BUF_record["code_pec"];
                            $valideCodesPec = array("0", "1", "2", "3", "X");
                            if (!in_array($value, $valideCodesPec)) {
                                $erreur = "Valeur $value incorrecte";
                                $commentaire = "1 prix par défaut";
                                controle_add_error("VID", $no_ligne, "Code prise en charge", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["code_pec_offset"], $BUF_offsets["code_pec_len"]);
                            }

                        }

                    }

                }

            }

            fclose($handle);

        }
    }

    if ($nbE > 0 || $nbW > 0) {

        $sqlcmd = <<<SQL
        UPDATE pmsi.p_imports
        SET nb_erreurs = nb_erreurs + $nbE,
            nb_avertissements = nb_avertissements + $nbW
        WHERE oid = $import_id
SQL;

        execute_sql($sqlcmd, $nbE, $nbW_rum );

    }

    
    commit_trans();
    
    logInfoMsg("FIN CONTROLE CONTROLE DE ANO (VIDHOSP OUT). $nb_vidhosp lus, $nbI informations, $nbW avertissements, $nbE erreurs graves");
}


function controle_rsa() {

    global $ENV_FINESS;

    global $import_id;

    global $file_RSS;
    global $file_RSA;
    global $file_TRA;

    global $file_exists_RSA;
    global $file_exists_TRA;
    
    global $versions_groupage;
    

    logInfoMsg("CONTROLE DES RSA");

    $nb = 0;
    $nbI = 0;
    $nbW = 0;
    $nbE = 0;
    
    $rss_ghm_array = array();
    $line_rss_array = array();
    $line_ghm_array = array();
    $line_sej_array = array();
    
    $rsa_linerss_array = array();
    
    $rss_sej_array = array();
    
    begin_trans();
    

    if ($file_exists_RSA) {
    
    
        // GHM par RSS (pour controle concordance)
        $nb_rss = 0;
        $der_rss = 0;
        $no_ligne = 0;
        
        $handle = @fopen($file_RSS, "r");
        if ($handle) {
            while (!feof($handle)) {
                $buffer = fgets($handle, 99999);
                
                $no_ligne++;
                if (trim($buffer) != "" && $no_ligne < 1000000000000000) {

                    $BUF_record = read_rum_line($buffer);
                    
                    if ($BUF_record["type_enregistrement"] == "RUM") {

                        
                        $no_rss =  get_numrss($BUF_record["no_rss"]);
                        
                        if ($no_rss != $der_rss) {
                            $nb_rss++;
                            $der_rss = $no_rss;
                            $rss_ghm_array[$nb_rss] = trim($BUF_record["ghm"]);
                        }
                        
                        $line_rss_array[$no_ligne] = $no_rss;
                        $line_ghm_array[$no_ligne] = $BUF_record["ghm"];
                        $line_sej_array[$no_ligne] = get_charAsNum($BUF_record["no_sejour_administratif"]);

                        $rss_sej_array[$BUF_record["no_rss"]] = $BUF_record["no_sejour_administratif"];

                    }
                }
            }
        }
        
        if ($file_exists_TRA) {
            
            $no_ligne = 0;
            
            $handle = @fopen($file_TRA, "r");
            if ($handle) {

                while (!feof($handle)) {
                    $buffer = fgets($handle, 99999);
                    
                    $no_ligne++;
                    if (trim($buffer) != "" && $no_ligne < 1000000000000000) {

                        $BUF_record = read_tra_line($buffer);

                        
                        if ($BUF_record["type_enregistrement"] == "TRA") {
                        
                            
                            $no_rsa =  $BUF_record["no_rsa"];
                            $doControlTRA_GHM = $BUF_record["doControlTRA_GHM"];
                            
                            $ligne_rss =  get_num($BUF_record["ligne_rss"]);

                            $traVersion = $ligne_rss === 0 ? "druide_2023" : "old";
                            if ($traVersion === "druide_2023"){
                                $rss_ghm_array[$no_rsa] = trim($BUF_record["ghm"]);
                                if ($rss_sej_array[$BUF_record["no_rss"]] != $BUF_record["no_sejour_administratif"]) {
									$erreur = "Non concordance entre TRA, RSA et RSS pour RSA " . $BUF_record["no_rsa"];
									$commentaire = "Le fichier RSA ne sera pas traité";
									controle_add_error("TRA", $no_ligne, "GHM", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, 0, 0);
								}
                            } else {
                                // Ancienne version
                                $no_sejour_administratif =  get_charAsNum($BUF_record["no_sejour_administratif"]);
								$ghm =  $BUF_record["ghm"];
								if ($line_sej_array[$ligne_rss] == $no_sejour_administratif) {
									$rss_ghm_array[$no_rsa] = trim($line_ghm_array[$ligne_rss]);
								}
								else {
									$erreur = "Non concordance entre TRA, RSA et RSS pour RSA " . $BUF_record["no_rsa"];
									$commentaire = "Le fichier RSA ne sera pas traité";
									controle_add_error("TRA", $no_ligne, "GHM", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, 0, 0);
								}
                            }
                        }
                    }
                }
            }
        }
        

        
        $no_ligne = 0;
        
        $nb_rsa = 0;
        
        $finess_error = FALSE;
        $format_error = FALSE;
        $finess_first = "";
        
        $pb_concordance = FALSE;
        
        $handle = @fopen($file_RSA, "r");
        if ($handle) {
            while (!feof($handle)) {
                $buffer = fgets($handle, 99999);
                
                $no_ligne++;
                if (trim($buffer) != "" && $no_ligne < 1000000000000000) {
                
                    $nb++;
                    
                    $BUF_record = read_rsa_line($buffer);
                    
                    if ($BUF_record["type_enregistrement"] == "RSA") {
                    
                        $BUF_offsets = $BUF_record["BUF_offsets"];
                    
                        $nb_rsa++;
                        $no_rsa =  $BUF_record["no_rsa"];

                        $decalage = FALSE;
                        $RSA_error = FALSE;
                        
                        if ($BUF_record["fmt_error"] != "" && $format_error == FALSE) {
                            $erreur = $BUF_record["fmt_error"];
                            $commentaire = "Le fichier est accepté par iCTI mais ne peut être envoyé aux tutelles";
                            controle_add_error("RSA", $no_ligne, "Format", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["version_format_offset"], $BUF_offsets["version_format_len"]);
                            $format_error = TRUE;
                        }
                    
                        // Finess
                        if (1 == 2) {
                        if ($BUF_record["finess"] != $ENV_FINESS && $finess_error == FALSE) {
                            $erreur = "Valeur " . $BUF_record["finess"] . " différente de $ENV_FINESS";
                            $commentaire = "Le fichier est erroné";
                            controle_add_error("RSA", $no_ligne, "Finess", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["finess_offset"], $BUF_offsets["finess_len"]);
                            $finess_error = TRUE;
                        }
                        }
                        if ($finess_first == "") {
                            $finess_first = $BUF_record["finess"];
                        }
                        
                        
                        
                        // Code sexe (si erreur, décalage)
                        if ($decalage == FALSE) {
                            $sexe = $BUF_record["sexe"];
                            if ($sexe != "1" && $sexe != "2" && $sexe != "3" ) {
                                $erreur = "Valeur $sexe incorrecte pour RSA " . $BUF_record["no_rsa"];
                                $commentaire = "Il y a peut-être un décalage dans l'enregistrement";
                                controle_add_error("RSA", $no_ligne, "Sexe", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["sexe_offset"], $BUF_offsets["sexe_len"]);
                                $decalage = TRUE;
                            }
                        }
                        
                        
                        
                        
                        
                        if ($decalage == FALSE) {
                        
                            // version groupage
                            $version_groupage = strtoupper($BUF_record["version_groupage"]);
                            if ($BUF_record["ghm"] != "") {
                                if (!in_array($version_groupage, $versions_groupage)) {
                                    $erreur = "Valeur $version_groupage incorrecte pour RSA " . $BUF_record["no_rsa"];
                                    $commentaire = "";
                                    controle_add_error("RSA", $no_ligne, "Version groupage", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["version_groupage_offset"], $BUF_offsets["version_groupage_len"]);
                                }
                            }
                            
                            // GHM

                            if ($BUF_record["ghm"] != "") {
                                if (! check_ghm($BUF_record["ghm"], $gravite, $erreur, $commentaire)) {
                                    $erreur = $erreur . " pour RSA " . $BUF_record["no_rsa"];
                                    controle_add_error("RSA", $no_ligne, "GHM", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["ghm_offset"], $BUF_offsets["ghm_len"]);
                                }

                            }
                            
                            if ($BUF_record["ghm_genrsa"] != "" && $BUF_record["ghm_genrsa"] != $BUF_record["ghm"]) {
                                if (! check_ghm($BUF_record["ghm_genrsa"], $gravite, $erreur, $commentaire)) {
                                    $erreur = $erreur . " pour RSA " . $BUF_record["no_rsa"];
                                    controle_add_error("RSA", $no_ligne, "GHM GENRSA", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["ghm_genrsa_offset"], $BUF_offsets["ghm_genrsa_len"]);
                                }

                            }
                                                        
                            if ($pb_concordance == FALSE) {
                                if ($doControlTRA_GHM && @$rss_ghm_array[$no_rsa] != trim($BUF_record["ghm_genrsa"])) {
                                    $erreur = "Non concordance entre RSA et RSS pour RSA " . $BUF_record["no_rsa"];
                                    $commentaire = "Le fichier RSA ne sera pas traité";
                                    controle_add_error("RSA", $no_ligne, "GHM", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["ghm_offset"], $BUF_offsets["ghm_len"]);
                                    $pb_concordance = TRUE;
                                }
                            }
                            
                            
                            
                            // RSA
                            if (! controle_check_num($BUF_record["no_rsa"],0,FALSE,$erreur,$commentaire)) {
                                $commentaire = "";
                                controle_add_error("RSA", $no_ligne, "Numéro RSA", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["no_rsa_offset"], $BUF_offsets["no_rsa_len"]);
                                $RSA_error = TRUE;
                            }
                            

                            
                            // mode entrée
                            if (! check_mode_entree($BUF_record["mode_entree"], $gravite, $erreur, $commentaire)) {
                                controle_add_error("RSA", $no_ligne, "Mode entrée", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["mode_entree_offset"], $BUF_offsets["mode_entree_len"]);
                            }
                            
                            // Provenance
                            if (! check_provenance($BUF_record["provenance"], $gravite, $erreur, $commentaire)) {
                                controle_add_error("RSA", $no_ligne, "Provenance", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["provenance_offset"], $BUF_offsets["provenance_len"]);
                            }

                            // Date sortie
                            if (! controle_check_num($BUF_record["mois_sortie"],0,false,$erreur,$commentaire)) {
                                $commentaire = "";
                                controle_add_error("RSA", $no_ligne, "Mois sortie", $buffer, $erreur, 4, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["mois_sortie_offset"], $BUF_offsets["mois_sortie_len"]);
                            }

                            
                            // Mode sortie
                            if (! check_mode_sortie($BUF_record["mode_sortie"], $gravite, $erreur, $commentaire)) {
                                controle_add_error("RSA", $no_ligne, "Mode sortie", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["mode_sortie_offset"], $BUF_offsets["mode_sortie_len"]);
                            }
                            
                            // Destination
                            if (! check_destination($BUF_record["destination"], $gravite, $erreur, $commentaire)) {
                                controle_add_error("RSA", $no_ligne, "Provenance", $buffer, $erreur, $gravite, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["destination_offset"], $BUF_offsets["destination_len"]);
                            }

                            // Nombre séances
                            if (! controle_check_num($BUF_record["nombre_seances"],2, TRUE,$erreur,$commentaire)) {
                                $commentaire = "0 pris par défaut";
                                controle_add_error("RSA", $no_ligne, "Nombre séances", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["nombre_seances_offset"], $BUF_offsets["nombre_seances_len"]);
                            }
                            
                            
                            // IGS
                            if (! controle_check_num($BUF_record["igs2"],3, TRUE,$erreur,$commentaire)) {
                                $commentaire = "0 pris par défaut";
                                controle_add_error("RSA", $no_ligne, "IGS 2", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["igs2_offset"], $BUF_offsets["igs2_len"]);
                            }
                            
                            // Top GHS Minoré
                            if (! controle_check_num($BUF_record["top_ghs_minore"], 1, TRUE, $erreur, $commentaire)) {
                                $commentaire = "0 pris par défaut";
                                controle_add_error("RSA", $no_ligne, "Top GHS minoré", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["top_ghs_minore"], $BUF_offsets["top_ghs_minore"]);
                            }
                            
                            // Top UHCD
                            
                            // Nb de zones de suppléments de radiothérapie
                            if(!controle_check_num($BUF_record["nb_rdth"], 1, TRUE, $erreur, $commentaire)){
                                $commentaire = "0 pris par défaut";
                                controle_add_error("RSA", $no_ligne, "Nb de suppl. de radiothérapie", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["igs2_offset"], $BUF_offsets["igs2_len"]);
                            }
                            
                            // Passage dans un lit dédié de soins palliatifs
                            
                            // Nombre de faisceaux
                            if(!controle_check_num($BUF_record["nb_faisceaux"], 1, TRUE, $erreur, $commentaire)){
                                $commentaire = "0 pris par défaut";
                                controle_add_error("RSA", $no_ligne, "Nombre de faisceaux", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $BUF_offsets["igs2_offset"], $BUF_offsets["igs2_len"]);
                            }
                            
                            // Suppléments de radiothérapie
                            $srdth = 0;
                            foreach ($BUF_record["supprdth"] as $supplement_rdth) {
                                $srdth++;
                                $commentaire = "";
                                // Vérification du GHS
                                if (!check_ghs($supplement_rdth["ghs"], $gravite, $erreur, $commentaire)) {
                                    controle_add_error("RSA", $no_ligne, "Supplément GHS de radiothérapie n°$srdth", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $supplement_rdth["ghs_offset"], $supplement_rdth["ghs_offset_len"]);
                                }
                                // Vérification du nombre de suppléments
                                if(!controle_check_num($supplement_rdth["nb_supplements"], 3, TRUE, $erreur, $commentaire)){
                                    $commentaire = "0 pris par défaut";
                                    controle_add_error("RSA", $no_ligne, "Nombre GHS de suppléments n°$srdth", $buffer, $erreur, 1, $commentaire, $nbI, $nbW, $nbE, $supplement_rdth["nb_supplements_offset"], $supplement_rdth["nb_supplements_len"]);
                                }
                            }
                        }

                        
                    }
                }
            
            }
            
            fclose($handle);
        
        }
    

    } else {
        //controle_add_error("FILE", 0, "", "", "Fichier des RSA absent", 4, "", $nbI, $nbW, $nbE);
    
    }
    
    
    
    if ($nbE > 0 || $nbW > 0) {

        $sqlcmd = "UPDATE pmsi.p_imports SET ";
        $sqlcmd = $sqlcmd . "nb_erreurs = nb_erreurs + $nbE, nb_avertissements = nb_avertissements + $nbW ";
        $sqlcmd = $sqlcmd . "WHERE oid = $import_id";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW_rsa );

    }
    
    commit_trans();
    
    logInfoMsg("FIN CONTROLE DES RSA. $nb lus, $nbI informations, $nbW avertissements, $nbE erreurs graves");
    
}

function controle_check_num($value, $maxLen=0, $facultatif = FALSE, &$error, &$commentaire) {

    $error = "";
    $commentaire = "";
    
    // Trim de la valeur.
    $valueToCheck = trim($value);
    
    // Si valeur facultative et que longueur = 0, pas de contrôle.
    if ($facultatif == TRUE && strlen($valueToCheck) == 0) {
        return TRUE;
    }
    
    // Contrôle de la longueur de la chaîne de caractères.
    if ($maxLen > 0) { // Si longueur max du champ $maxLen > 0 :
        if (strlen($valueToCheck) == 0 || strlen($valueToCheck) > $maxLen) { // 1 <= longueur du champ <= $maxLen.
            $error = "Valeur numérique $value incorrecte (longueur $maxLen obligatoire)";
            return FALSE;
        }
    }
    
    // Contrôle de la nature de la chaîne de caractères.
    if (! is_numeric($valueToCheck) ) {
        $error = "Valeur $value non numérique";
        return FALSE;
    }
    
    return TRUE;
}

function get_num($value, $defaultValue=0) {

    if (! is_numeric($value) ) {
        return $defaultValue;
    }
    
    return $value + 0;
}

/**
    Fonction spécifique pour les numéros de RSS afin d'éviter
    les notations scientifiques générées parfois par la fonction get_num($val, $def)
*/
function get_numrss($value, $defaultValue=0) {

    if (! is_numeric($value) ) {
        return $defaultValue;
    }
    
    $var = ltrim($value, '0');  // vire les leading zeros
    
    // retourne 0 si la chaine est vide (= pas de no_rss)
    if (strlen($var) > 0) { 
        return $var;
    } 
    else { 
        return 0;
    }
}

function get_charAsNum($value, $defaultValue="0") {

    if (! is_numeric($value) ) {
        return $defaultValue;
    }
    
    $check = true;
    while ($check):
    $check = false;
    if (strlen($value) > 0) {
        if (substr($value,0,1) == "0") {
            $value = trim(substr($value,1));
            $check = true;
        }
    }
    endwhile;
    
    if ($value == "") {
        return $defaultValue;
    }
    
    return $value;
}


function controle_check_date($value, &$error, &$commentaire, $check_possible=false) {

    $error = "";
    $commentaire = "";
    
    
    
    
    $pos = stripos($value, "/");
    if ($pos === false) {
        if (strlen($value) == 7) {
            $value = "0$value";
        }
        if (strlen($value) != 8) {
            if (strlen($value) == 6) {
                // Format AAMMJJ
                $day = substr($value, 4, 2);
                $month = substr($value, 2, 2);
                $year = substr($value, 0, 2);;
            }
            else {
                $error = "Format date $value incorrect";
                return FALSE;
            }
        }
        else {

            $date12 = substr($value, 0, 2);
            $date34 = substr($value, 2, 2);
            $date56 = substr($value, 4, 2);
            $date78 = substr($value, 6, 2);

            if (get_num($date56) == 0) {
                $date56 = "20";
            }
        
        }
        
        if (strlen($value) == 6) {
            // Format AAMMJJ : ne rien faire pour ne pas écraser $day, $month et $year
        }
        else if (get_num($date56) <= 12) {
            $day = $date78;
            $month = $date56;
            $year = "$date12$date34";
        }
        else {
            $day = $date12;
            $month = $date34;
            $year = "$date56$date78";
        }
        
    }
    
    else {
        
        //enlever heure
        $value2 = $value;
        $pos = stripos($value, " ");
        if ($pos === false) {
        }
        else {
            $value2 = substr($value, 0, $pos);
        }
        
        // décomposer
        $date_array = split("/", $value2);
        if (count($date_array) != 3) {
            $error = "Format date $value incorrect";
            return FALSE;
        }
        $date1 = $date_array[0];
        $date2 = $date_array[1];
        $date3 = $date_array[2];
        
        if ($date1 > 1000) {
            $year = $date1;
            $month = $date2;
            $day = $date3;
        }
        else {
            $day = $date1;
            $month = $date2;
            $year = $date3;
        }
        if ($month < 10 && strlen($month) == 1) {
            $month = "0$month";
        }
        if ($day < 10 && strlen($day) == 1) {
            $day = "0$day";
        }
    
    }
    // Vérifie ou non si l'année de la date est crédible ou pas
    if ($check_possible == true && strlen($value) == 6) {
        if (intval($year) < 1890 || intval($year) > 2100) {
            $error = "Date $value : année incorrecte";
            return FALSE;
        }
    }
    
    
    if (! checkdate($month, $day, $year) ) {
        $error = "Format date $value incorrect";
        return FALSE;
    }
    
    return TRUE;
}

function default_birth_date($value) {

    $date = "19620418";
    
    if (get_num($value) == 0) {
        return $date;
    }
    
    $pos = stripos($value, "/");
    if ($pos === false) {
        if (strlen($value) == 8) {
            $date12 = substr($value, 0, 2);
            $date34 = substr($value, 2, 2);
            $date56 = substr($value, 4, 2);
            $date78 = substr($value, 6, 2);

            if (get_num($date56) == 0) {
                $date56 = "20";
            }
        }
        
        if (get_num($date56) <= 12) {
            $day = $date78;
            $month = $date56;
            $year = "$date12$date34";
        }
        else {
            $day = $date12;
            $month = $date34;
            $year = "$date56$date78";
        }
        
    }
    
    else {
        //enlever heure
        $value2 = $value;
        $pos = stripos($value, " ");
        if ($pos === false) {
        }
        else {
            $value2 = substr($value, 0, $pos);
        }
        
        // décomposer
        $date_array = split("/", $value2);
        if (count($date_array) == 3) {
            
            $date1 = $date_array[0];
            $date2 = $date_array[1];
            $date3 = $date_array[2];
            
            if ($date1 > 1000) {
                $year = $date1;
                $month = $date2;
                $day = $date3;
            }
            else {
                $day = $date1;
                $month = $date2;
                $year = $date3;
            }
            if ($month < 10 && strlen($month) == 1) {
                $month = "0$month";
            }
            if ($day < 10 && strlen($day) == 1) {
                $day = "0$day";
            }
        }
    
    }

    
    if (!checkdate($month, $day, $year) ) {
        if ($year >= 1900 && $year <= 2015) {
            $month = "04";
            $day = "18";
        }
        else {
            $year = "1962";
            $month = "04";
            $day = "18";
        }
    }
    else {
        if ($year < 1900 || $year > 2050) {
            $year = "1962";
            $month = "04";
            $day = "18";
        }
    }   
    
    $date = "$year$month$day";
    
    return $date;
}

function get_date_or_null($value) {
    $date = get_date_AAAAMMJJ($value);
    return ($date != "" AND $date != '00000000') ? "'" . $date . "'::date" : "null";
}

function get_date_AAAAMMJJ($value) {

    $date = "00010101";
    if (! is_numeric($value) ) {
        return $date;
    }
    $date12 = substr($date, 0, 2);
    $date34 = substr($date, 2, 2);
    $date56 = substr($date, 4, 2);
    $date78 = substr($date, 6, 2);

    
    $pos = stripos($value, "/");
    if ($pos === false) {
        if (strlen($value) == 7) {
            $value = "0$value";
        }
        if (strlen($value) != 8) {

        }
        else {

            $date12 = substr($value, 0, 2);
            $date34 = substr($value, 2, 2);
            $date56 = substr($value, 4, 2);
            $date78 = substr($value, 6, 2);

            if (get_num($date56) == 0) {
                $date56 = "20";
            }
        
        }
        
        if (get_num($date56) <= 12) {
            $day = $date78;
            $month = $date56;
            $year = "$date12$date34";
        }
        else {
            $day = $date12;
            $month = $date34;
            $year = "$date56$date78";
        }

        if(intval($month) > 12 || intval($month) <= 0 || intval($day) > 31 || intval($day) <= 0 ) {
            $date = "";
        } else {
            $date = $year . $month . $day;
        }
        
    } else {
        //enlever heure
        $value2 = $value;
        $pos = stripos($value, " ");
        if ($pos === false) {
        }
        else {
            $value2 = substr($value, 0, $pos);
        }
        
        // décomposer
        $date_array = split("/", $value2);
        if (count($date_array) != 3) {
            $error = "Format date $value incorrect"; 
            return FALSE;
        }
        $date1 = $date_array[0];
        $date2 = $date_array[1];
        $date3 = $date_array[2];
        
        if ($date1 > 1000) {
            $year = $date1;
            $month = $date2;
            $day = $date3;
        }
        else {
            $day = $date1;
            $month = $date2;
            $year = $date3;
        }
        if ($month < 10 && strlen($month) == 1) {
            $month = "0$month";
        }
        if ($day < 10 && strlen($day) == 1) {
            $day = "0$day";
        }
        
        $date = $year . $month . $day;
    
    }

    return $date;
}



function controle_add_error($data_type, $no_ligne, $champ, $ligne, $erreur, $gravite, $commentaire, &$nbI, &$nbW, &$nbE, $offset=0, $len=0) {


    global $import_id;

    $offset = get_num($offset);
    $len = get_num($len);
    
    if ($gravite > 0) {
        $champSQL = toSQL($champ);
        $ligneSQL = toSQL(substr($ligne,0,10000));
        $erreurSQL = toSQL($erreur);
        $commentaireSQL = toSQL($commentaire);
    
        $sqlcmd = "INSERT INTO pmsi.p_imports_controles( ";
        $sqlcmd = $sqlcmd . "import_id,  ";
        $sqlcmd = $sqlcmd . "data_type,  ";
        $sqlcmd = $sqlcmd . "no_ligne,  ";
        $sqlcmd = $sqlcmd . "champ,  ";
        $sqlcmd = $sqlcmd . "ligne,  ";
        $sqlcmd = $sqlcmd . "erreur,  ";
        $sqlcmd = $sqlcmd . "commentaire,  ";
        $sqlcmd = $sqlcmd . "gravite, ";
        $sqlcmd = $sqlcmd . "position, ";
        $sqlcmd = $sqlcmd . "longueur ";
        $sqlcmd = $sqlcmd . ") ";
        $sqlcmd = $sqlcmd . "VALUES( ";
        $sqlcmd = $sqlcmd . "$import_id,  ";
        $sqlcmd = $sqlcmd . "'$data_type',  ";
        $sqlcmd = $sqlcmd . "$no_ligne,  ";
        $sqlcmd = $sqlcmd . "'$champSQL',  ";
        $sqlcmd = $sqlcmd . "'$ligneSQL',  ";
        $sqlcmd = $sqlcmd . "'$erreurSQL',  ";
        $sqlcmd = $sqlcmd . "'$commentaireSQL',  ";
        $sqlcmd = $sqlcmd . "$gravite,  ";
        $sqlcmd = $sqlcmd . "$offset, ";
        $sqlcmd = $sqlcmd . "$len ";
        $sqlcmd = $sqlcmd . ") ";
        
        $toResult = execute_sql($sqlcmd, $nbE );
        
        $grav = "INFO";
        if ($gravite >= 4) {
            $grav = "ERROR";
            $nbE++;
        }
        else {
            if ($gravite > 0) {
                $grav = "WARNING";
                $nbW++;
            }
            else {
                $nbI++;
            }
        }
        
        if ($data_type != "EXEC") {
            $message = "Ligne $data_type $no_ligne : $champ (gravité $gravite) - $erreur - $commentaire";
        }
        else {
            $message = "Exécution (gravité $gravite) - $erreur - $commentaire";
        }

        switch ($grav) {
            case "INFO":
                logInfoMsg($message);
                break;
            case "ERROR":
                logErrorMsg($message);
                break;
            case "WARNING":
                logWarnMsg($message);
                break;
        }
    }
}


// Traitement d'un import
function generation() {

    global $ENV_TYPEETS;
    global $import_id;

    global $file_exists_RSF;
    global $file_exists_FCP;

    global $file_exists_TSP;
    
    logInfoMsg("GENERATION N° $import_id");
    
    restauration_fichiers();
    restauration_donnees_complementaires(); // SUPPR

    generation_initialisation();
    
    generation_initialisation_parametres();

    generation_ium();
    
    generation_med(); // SUPPR
    generation_rum();

    
    //if ($ENV_TYPEETS != "1") {
        generation_rsa();
    //}
    
    if ($ENV_TYPEETS == "1") {
        generation_rsf_sans_rss();
        generation_rsf();
    }
    
    if ($ENV_TYPEETS != "1" ) {
        if ($file_exists_RSF) {
            generation_rsf_sans_rss();
            generation_rsf();
        }
    }
    
    generation_rum_post_traitements() ;
    
    if ($file_exists_FCP == true) {
        generation_fichcomp();
    }
    if ($file_exists_TSP == true) {
        generation_fichsup();
    }
    if ($ENV_TYPEETS != "1") {
        generation_ano_vidhosp();
        generation_ctl();
        valorisation_public();
    }
    
    // Lecture des séjours non pris en compte dans la valorisation hors ATU, FFM, FSD, VDE et SE.
    generation_npec_valorisation();
    
    generation_rsf_post_traitements() ;
    
    // Validation des données générées
    generation_validation_tables() ;
    
    // Traitements sur toute la base
    generation_traitements_finaux() ;
    
    
    
    generation_validation();
    
    suppression_fichiers();
    
    
    logInfoMsg("FIN GENERATION N° $import_id");

}

/**
 * Lit le fichier *.val.err.txt du RSS.out.zip et le charge dans l'array $val_array.
 *
 */
function generation_npec_valorisation() {
    global $file_VAL;
    global $file_exists_VAL;
    global $val_array;

    $val_array = array();
    
    if ($file_exists_VAL) {
        logInfoMsg("LECTURE SEJOURS NON PRIS EN COMPTE");
        
        $no_ligne = 0;
        $startReading = false;
        $handle = fopen($file_VAL, "r");
        if ($handle) {
            while (!feof($handle)) {
                $no_ligne++;
                $buffer = fgets($handle, 99999);
                
                if ($no_ligne < 100000000000) {
                    if (trim($buffer) == 'NUMTEST;NUMRSS;NUMADMIN;GHM') {
                        $startReading = true;
                    } else {
                        if (strpos($buffer, ';') !== false) {
                            if ($startReading) {
                                $val_array[] = explode(';', str_replace('"', '', $buffer));
                            }
                        } else {
                            $startReading = false;
                        }
                    }
                }
            }
        }
        
        fclose($handle);
        
        logInfoMsg("FIN LECTURE SEJOURS NON PRIS EN COMPTE");
    }
}

// Traitement d'un import
function generations_fin() {

    global $iCTI_connexion;
    global $iCTI_cache;
    global $omitEssentiels;
	
	global $ENV_OPTIMISATIONS_VUES_MATERIALISEES;
    
    echo PHP_EOL;
    
    vacuum_tables();
    
    set_oids();
    //analyse_all_tables();
	
	// Purge des imports
	$toResult = execute_sql("SELECT pmsi.cti_purge_import()", $nbE, $nbW );
    commit_trans();
    
    // Lancement du calcul des indicateurs Essentiels
    if ($omitEssentiels === false) {
        logInfoMsg("CALCUL DES INDICATEURS ESSENTIELS MCO");
        $exe = __ROOT__ . '/modules/outils/dashboard/iCTI_aggregateCtiIndicators';

        if (OperatingSystem::isWindows()){
            $exe .= '.exe';
            $submitCmd = "$exe -m pmsi  -e";
        } else {
            $exe .= '.php';
            $submitCmd = "php $exe -m pmsi  -e";
        }

        if (file_exists($exe)) {
            exec($submitCmd);
        }
        else {
            logErrorMsg("La fonction de calcul des essentiels MCO est absente");
        }
    }
    else {
        logInfoMsg("Omission du calcul des Essentiels");
    }
	
	if ($ENV_OPTIMISATIONS_VUES_MATERIALISEES == '1') {
		logInfoMsg("Performance et optimisations. Rafraichissement des vues matérialisées.");
		$toResult = execute_sql("SELECT pmsi.cti_rafraichir_vues_materialisees()", $nbE, $nbW);
	}
    
    // retraitement du cache (ancienne version)
    if ($iCTI_cache == "true") {
        logInfoMsg("RECONSTITUTION DU CACHE");
        $result = $iCTI_connexion->query("SELECT cti_cache_reload as log from cache.cti_cache_reload('iCTI_pmsi', true)");

        $record = pg_fetch_array($result);
        if ($record != FALSE) {
            $log = trim($record["log"]);
        }
        logInfoMsg("FIN RECONSTITUTION DU CACHE ($log)");
    }
    
    // retraitement du cache (nouvelle version)
    logInfoMsg("Nettoyage cache");
    cleanAllCache("iCTI_pmsi");
    
    echo PHP_EOL;
}


function restauration_fichiers() {
    global $iCTI_connexion;
    global $ENV_TYPEETS;
    
    global $import_id;

    global $file_RSS;
    global $file_RSF;
    global $file_FCP;
    global $file_ANO;
    global $file_RSA;
    global $file_CTL;
    global $file_TRA;
    global $file_VAL;
    global $file_LEG;
    global $file_IUM;
    global $file_VSJ;
    global $file_VSE;
    global $file_TSP;
    
    global $file_exists_RSS;
    global $file_exists_RSF;
    global $file_exists_FCP;
    global $file_exists_ANO;
    global $file_exists_RSA;
    global $file_exists_CTL;
    global $file_exists_TRA;
    global $file_exists_VAL;
    global $file_exists_LEG;
    global $file_exists_IUM;
    global $file_exists_VSJ;
    global $file_exists_VSE;
    global $file_exists_TSP;
    
    logInfoMsg("RESTAURATION FICHIERS");
    
    // Creation tables copie directe en table
    $sqlcmd = "DROP TABLE IF EXISTS w_out_diap;
                CREATE TEMP TABLE w_out_diap (data text);";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    $sqlcmd = "DROP TABLE IF EXISTS w_out_porg;
                CREATE TEMP TABLE w_out_porg (data text);";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    $sqlcmd = "DROP TABLE IF EXISTS w_out_pie;
                CREATE TEMP TABLE w_out_pie (data text);";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    $sqlcmd = "DROP TABLE IF EXISTS w_out_complog;
                CREATE TEMP TABLE w_out_complog (data text);";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    // Creation fichiers de travail
    $file_RSS = temp_file();
    $file_RSF = temp_file();
    $file_FCP = temp_file();
    $file_ANO = temp_file();
    $file_RSA = temp_file();
    $file_CTL = temp_file();
    $file_TRA = temp_file();
    $file_VAL = temp_file();
    $file_LEG = temp_file();
    $file_IUM = temp_file();
    $file_VSJ = temp_file();
    $file_VSE = temp_file();
    $file_TSP = temp_file();
    
    $file_DIAP = temp_file();
    $file_PORG = temp_file();
    $file_PIE = temp_file();
    $file_COMPLOG = temp_file();
    
    $file_ZIN = temp_file();
    $file_ZOU = temp_file();
    $file_ZIF = temp_file();
    
    @unlink($file_RSS);
    @unlink($file_RSF);
    @unlink($file_FCP);
    @unlink($file_ANO);
    @unlink($file_RSA);
    @unlink($file_CTL);
    @unlink($file_TRA);
    @unlink($file_VAL);
    @unlink($file_LEG);
    @unlink($file_IUM);
    @unlink($file_VSJ);
    @unlink($file_VSE);
    @unlink($file_TSP);
    
    @unlink($file_DIAP);
    @unlink($file_PORG);
    @unlink($file_PIE);
    @unlink($file_COMPLOG);
    
    // restauration IN et out.zip
    @unlink($file_ZIN);
    @unlink($file_ZOU);
    @unlink($file_ZIF);


    $result = $iCTI_connexion->query("SELECT data_type, data FROM pmsi.p_imports_data 
                WHERE import_id = $import_id 
                AND data_type IN ('ZIN' , 'ZOU', 'ZIF')
                ORDER by data_num  ");
    $ok = TRUE;
    while ($ok == TRUE) {
        $ok = FALSE;
        $record = pg_fetch_array($result);
        if ($record != FALSE) {
            $ok = TRUE;
            $data_type = trim($record["data_type"]);
            $data = $record["data"];
            
            if ($data_type == "ZIN") {
                $handle = fopen($file_ZIN, 'a');
                fwrite($handle, uncompress(pg_unescape_bytea($data)));
                fclose($handle);
            }
            if ($data_type == "ZOU") {
                $handle = fopen($file_ZOU, 'a');
                fwrite($handle, uncompress(pg_unescape_bytea($data)));
                fclose($handle);
            }
            if ($data_type == "ZIF") {
                $handle = fopen($file_ZIF, 'a');
                fwrite($handle, uncompress(pg_unescape_bytea($data)));
                fclose($handle);
            }

        }
    }
        
    // Si fichier IN.ZIP, decompression
    if (file_exists($file_ZIN)) {
        logInfoMsg("Fichier RSS IN.ZIP restauré, décompression");

        // Druide a fait une mise à jour, dans certains cas, seul les fichiers rss.ini sont présent
        // Si seul les .ini sont présent, on récupère ceux là
        // Sinon on utilise les rss.txt
        $zipIni = zip_open(realpath($file_ZIN));
        $rssIniOnly = true;
        $rsfIniOnly = true;
        while ($file = zip_read($zipIni)) {
            $filenameIni = zip_entry_name($file);
            if (stripos($filenameIni, "rss.txt")  > -1 ){
                $rssIniOnly = false;
            }
            if (stripos($filenameIni, "rsf.txt")  > -1 ){
                $rsfIniOnly = false;
            }
        }
        zip_close($zipIni);
        
        $zip = zip_open(realpath($file_ZIN));

        if ($zip) {
			while ($zip_entry = zip_read($zip)) {
				if (zip_entry_open($zip, $zip_entry)) {
					$filename = trim(zip_entry_name($zip_entry));
                    $filesuffix = substr($filename, strlen($filename) - 7 , 7);
                    $filesuffix2 = substr($filename, strlen($filename) - 10 , 10);

                    $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
                    $buf = str_replace("\r\n", "\n", $buf);
                    if ($filesuffix == "rss.txt" || ($rssIniOnly === true && stripos($filename, "rss.ini.txt")  > -1)) {
                        file_put_contents($file_RSS, $buf);
                        logInfoMsg("Fichier $filename décompressé");
                    }
                    if ($filesuffix == "rsf.txt" || ($rsfIniOnly === true && stripos($filename, "rsf.ini.txt")  > -1)) {
                        file_put_contents($file_RSF, $buf);
                        logInfoMsg("Fichier $filename décompressé");
                    }
                    if ($filesuffix == "dmi.txt") {
                        file_put_contents($file_FCP, "\n$buf", FILE_APPEND );
                        logInfoMsg("Fichier $filename décompressé");
                    }
                    if ($filesuffix == "med.txt") {
                        file_put_contents($file_FCP, "\n$buf", FILE_APPEND );
                        logInfoMsg("Fichier $filename décompressé");
                    }
                    if ($filesuffix2 == "medatu.txt" || search_fichcomp_atu($buf) === true) {
                        file_put_contents($file_FCP, "\n$buf", FILE_APPEND );
                        logInfoMsg("Fichier $filename décompressé");
                        if ($filesuffix2 != "medatu.txt") { echo " (FICHCOMP Médicaments ATU)";}
                    }
                    if ($filesuffix2 == "transp.txt") {
                        file_put_contents($file_FCP, "\n$buf", FILE_APPEND );
                        logInfoMsg("Fichier $filename décompressé");
                    }
                    if ($filesuffix == "ium.txt") {
                        file_put_contents($file_IUM, $buf);
                        logInfoMsg("Fichier $filename décompressé");
                    }
                    zip_entry_close($zip_entry);
                }
            }
            zip_close($zip);
        }
        @unlink($file_ZIN);
    }
    
    if (file_exists($file_ZOU)) {
        logInfoMsg("Fichier RSS OUT.ZIP restauré, décompression");

        $zip = @zip_open(realpath($file_ZOU));

        if ($zip) {
            
            while ($zip_entry = zip_read($zip)) {

                if (zip_entry_open($zip, $zip_entry, "r")) {

                    $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
                    
                    $file_name = trim(zip_entry_name($zip_entry));
                    
                    $filename = zip_entry_name($zip_entry);
                    $filesuffix = substr($filename, strlen($filename) - 4 , 4);
                    $filesuffix2 = substr($filename, strlen($filename) - 8 , 8);
                    $filesuffix3 = substr($filename, strlen($filename) - 5 , 5);
                    $filesuffix4 = substr($filename, strlen($filename) - 13 , 13);
                    $filesuffix5 = strtolower(substr($filename, strlen($filename) - 12 , 12));
                    
                    if ($filesuffix == ".rsa") {
                        file_put_contents($file_RSA, $buf);
                        logInfoMsg("Fichier $filename décompressé");
                    }
                    if ($filesuffix == ".ano") {
                        file_put_contents($file_ANO, $buf);
                        logInfoMsg("Fichier $filename décompressé");
                    }
                    if ($filesuffix == ".leg") {
                        file_put_contents($file_LEG, $buf);
                        logInfoMsg("Fichier $filename décompressé");
                    }
                    if ($filesuffix2 == ".tra.txt") {
                        file_put_contents($file_TRA, $buf);
                        logInfoMsg("Fichier $filename décompressé");
                    }
                    if ($file_name == "ctl_mt2a.detail.log.csv") {
                        file_put_contents($file_CTL, $buf);
                        logInfoMsg("Fichier $filename décompressé");
                    }
                    if (strpos($filename, ".val.err.txt") !== false) {
                        file_put_contents($file_VAL, $buf);
                        logInfoMsg("Fichier $filename décompressé");
                    }
                    // Pour fichier DIAP, copie directe dans une table
                    if ($filesuffix3 == ".diap") {
                        file_put_contents($file_DIAP, $buf);
                        $pg_file = str_replace("\\","/",realpath($file_DIAP));
                        $sqlcmd = "COPY w_out_diap FROM '$pg_file' WITH DELIMITER AS E'\01';";
                        $toResult = execute_sql($sqlcmd, $nbE, $nbW );
                        commit_trans();
                        logInfoMsg("Fichier $filename décompressé");
                    }
                    // Pour fichier PORG, copie directe dans une table
                    if ($filesuffix3 == ".porg") {
                        file_put_contents($file_PORG, $buf);
                        $pg_file = str_replace("\\","/",realpath($file_PORG));
                        $sqlcmd = "COPY w_out_porg FROM '$pg_file' WITH DELIMITER AS E'\01';";
                        $toResult = execute_sql($sqlcmd, $nbE, $nbW );
                        commit_trans();
                        logInfoMsg("Fichier $filename décompressé");
                    }
                    // Pour fichier PIE, copie directe dans une table
                    if ($filesuffix == ".pie") {
                        file_put_contents($file_PIE, $buf);
                        $pg_file = str_replace("\\","/",realpath($file_PIE));
                        $sqlcmd = "COPY w_out_pie FROM '$pg_file' WITH DELIMITER AS E'\01';";
                        $toResult = execute_sql($sqlcmd, $nbE, $nbW );
                        commit_trans();
                        logInfoMsg("Fichier $filename décompressé");
                    }
                    // Pour fichier COMP.LOG.TXT, copie directe dans une table
                    if ($filesuffix4 == ".comp.log.txt" || $filesuffix5 == ".atu.err.txt") {
                        file_put_contents($file_COMPLOG, $buf);
                        $pg_file = str_replace("\\","/",realpath($file_COMPLOG));
                        $sqlcmd = "COPY w_out_complog FROM '$pg_file' WITH DELIMITER AS E'\01';"; 
                        $toResult = execute_sql($sqlcmd, $nbE, $nbW );
                        commit_trans();
                        logInfoMsg("Fichier $filename décompressé");
                    }
                    zip_entry_close($zip_entry);
                }
            }
            zip_close($zip);
        }
        @unlink($file_ZOU);
    }
    
    // Si fichier RSF IN.ZIP, decompression
    if (file_exists($file_ZIF)) {
        logInfoMsg("Fichier RSF IN.ZIP restauré, décompression");
        
        $qrsfini = FALSE;

        $zip = @zip_open(realpath($file_ZIF));

        if ($zip) {
            
            while ($zip_entry = zip_read($zip)) {

                if (zip_entry_open($zip, $zip_entry)) {
                    
                    $filename = trim(zip_entry_name($zip_entry));
                    $filesuffix = substr($filename, strlen($filename) - 7 , 7);
                    $filesuffix2 = substr($filename, strlen($filename) - 11 , 11);

                    if ($filesuffix == "rsf.txt" && $qrsfini == FALSE) {
                        $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
                        file_put_contents($file_RSF, $buf);
                        logInfoMsg("Fichier $filename décompressé");
                    }
                    
                    if ($filesuffix2 == "rsf.ini.txt") {
                        $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
                        file_put_contents($file_RSF, $buf);
                        logInfoMsg("Fichier $filename décompressé");
                        $qrsfini = TRUE;
                    }
                    zip_entry_close($zip_entry);
                }
            }
            zip_close($zip);
        }
        @unlink($file_ZIF);
    }
    
    // Restauration autres fichiers
    $result = $iCTI_connexion->query("SELECT data_type, data 
        FROM pmsi.p_imports_data 
        WHERE import_id = $import_id AND data_type NOT IN ('ZIN' , 'ZOU')
        ORDER by data_num  ");

    $ok = TRUE;
    while ($ok == TRUE) {
        $ok = FALSE;
        $record = pg_fetch_array($result);
        if ($record != FALSE) {
            $ok = TRUE;
            $data_type = trim($record["data_type"]);
            $data = $record["data"];
            
            if ($data_type == "RSS") {
                $handle = fopen($file_RSS, 'a');
                fwrite($handle, uncompress(pg_unescape_bytea($data)));
                fclose($handle);
            }
            if ($data_type == "RSF") {
                $handle = fopen($file_RSF, 'a');
                fwrite($handle, uncompress(pg_unescape_bytea($data)));
                fclose($handle);
            }
            if ($data_type == "FCP") {
                $handle = fopen($file_FCP, 'a');
                fwrite($handle, uncompress(pg_unescape_bytea($data)));
                fclose($handle);
            }
            if ($data_type == "RSA") {
                $handle = fopen($file_RSA, 'a');
                fwrite($handle, uncompress(pg_unescape_bytea($data)));
                fclose($handle);
            }
            if ($data_type == "VSJ") {
                $handle = fopen($file_VSJ, 'a');
                fwrite($handle, uncompress(pg_unescape_bytea($data)));
                fclose($handle);
            }
            if ($data_type == "VSE") {
                $handle = fopen($file_VSE, 'a');
                fwrite($handle, uncompress(pg_unescape_bytea($data)));
                fclose($handle);
            }
            if ($data_type == "TSP") {
                $handle = fopen($file_TSP, 'a');
                fwrite($handle, uncompress(pg_unescape_bytea($data)));
                fclose($handle);
            }
        }
    }

    $file_exists_RSS = false;
    $file_exists_RSF = false;
    $file_exists_FCP = false;
    $file_exists_ANO = false;
    $file_exists_RSA = false;
    $file_exists_CTL = false;
    $file_exists_TRA = false;
    $file_exists_VAL = false;
    $file_exists_LEG = false;
    $file_exists_IUM = false;
    $file_exists_VSJ = false;
    $file_exists_VSE = false;
    $file_exists_TSP = false;
    
    if (file_exists($file_RSS)) {
        logInfoMsg("Fichier RSS restauré");
        $file_exists_RSS = true;
    }
    if (file_exists($file_RSF)) {
        logInfoMsg("Fichier RSF restauré");
        $file_exists_RSF = true;
    }
    if (file_exists($file_FCP)) {
        logInfoMsg("Fichier FICHCOMP restauré");
        $file_exists_FCP = true;
    }
    if (file_exists($file_ANO)) {
        logInfoMsg("Fichier VIDHOSP ANO restauré");
        $file_exists_ANO = true;
    }
    if (file_exists($file_RSA)) {
        logInfoMsg("Fichier RSA restauré");
        $file_exists_RSA = true;
    }
    if (file_exists($file_CTL)) {
        logInfoMsg("Fichier CTLM2T2 restauré");
        $file_exists_CTL = true;
    }
    else {
        if ($ENV_TYPEETS == "2" || $ENV_TYPEETS == "3") {
            controle_add_error("FILE", 0, "", "", "Fichier de contrôle de la valorisation des séjours absent (ctl_mt2a)", 1, "", $nbI, $nbW, $nbE);
        };
    }
    if (file_exists($file_TRA)) {
        logInfoMsg("Fichier TRA restauré");
        $file_exists_TRA = true;
    }
    if (file_exists($file_VAL)) {
        logInfoMsg("Fichier VAL restauré");
        $file_exists_VAL = true;
    }
    if (file_exists($file_LEG)) {
        logInfoMsg("Fichier LEG restauré");
        $file_exists_LEG = true;
    }
    if (file_exists($file_IUM)) {
        logInfoMsg("Fichier des Unités médicales restauré");
        $file_exists_IUM = true;
    }
    if (file_exists($file_VSJ)) {
        logInfoMsg("Fichier de valorisation des séjours restauré");
		if (filesize($file_VSJ) > 2000) {
			$file_exists_VSJ = true;
		}
		else {
			controle_add_error("FILE", 0, "", "", "Taille du fichier de valorisation des séjours inférieure à 2000. Le fichier ne sera pas traité", 0, "", $nbI, $nbW, $nbE);
		}
    }
    if (file_exists($file_VSE)) {
        logInfoMsg("Fichier de valorisation des ACE restauré");
		if (filesize($file_VSE) > 2000) {
			$file_exists_VSE = true;
		}
		else {
			controle_add_error("FILE", 0, "", "", "Taille du fichier de valorisation des ACE inférieure à 2000. Le fichier ne sera pas traité", 0, "", $nbI, $nbW, $nbE);
		}
    }
    if (file_exists($file_TSP)) {
        logInfoMsg("Fichier FICHSUP transports restauré");
        $file_exists_TSP = true;
    }
	
	if ($ENV_TYPEETS == "2" || $ENV_TYPEETS == "3") {
		if ($file_exists_VSJ == false) {
			controle_add_error("FILE", 0, "", "", "Fichier de valorisation des séjours absent ou incorrect", 4, "", $nbI, $nbW, $nbE);
		}
		if ($file_exists_VSE == false) {
			controle_add_error("FILE", 0, "", "", "Fichier de valorisation des ACE absent ou incorrect", 4, "", $nbI, $nbW, $nbE);
		}
    };
    
    logInfoMsg("FIN RESTAURATION FICHIERS");
}

/**
 * Fonction qui lit la première ligne d'un fichier et tente d'identifier un fichier de type fichcomp ATU
 */
function search_fichcomp_atu($content) {
    
    $found = false;
    
	$sub_content = substr($content, 0, 200);
    $lines = explode(PHP_EOL, $sub_content);
    $first_line = rtrim($lines[0], "\r\n");
    // Détection du format FICHCOMP en vigueur au 01 mars 2016
    // On vérifie la longueur de l'enregistrement, la présence au bon endroit du type d'enregistrement 09 et la présente au bon endroit d'une date au format DDMMYYYY
    if (    strlen($first_line) == 105 &&
            substr($first_line, 9, 2) == '09' &&
            checkdate(intval(substr($first_line, 33, 2)), intval(substr($first_line, 31, 2)), intval(substr($first_line, 35,4))) == true
        ) {
        $found = true;
    }
    unset($lines);
    return $found;
}

function restauration_donnees_complementaires() {
    global $iCTI_connexion;
    
    global $import_id;
    
    global $file_MED;
    global $file_RSSMED;
    global $file_RSSNOM;
    global $file_ACTMED;
    
    
    global $file_exists_MED;
    global $file_exists_RSSMED;
    global $file_exists_RSSNOM;
    global $file_exists_ACTMED;
    
    
    logInfoMsg("RESTAURATION DONNEES COMPLEMENTAIRES");
    
    $file_MED = temp_file();
    $file_RSSMED = temp_file();
    $file_RSSNOM = temp_file();
    $file_ACTMED = temp_file();

    @unlink($file_MED);
    @unlink($file_RSSMED);
    @unlink($file_RSSNOM);
    @unlink($file_ACTMED);

    // Restauration autres fichiers
    
    $result = $iCTI_connexion->query("SELECT data_type, data 
        FROM pmsi.p_imports_data 
        WHERE import_id = $import_id AND data_type IN ('MED' , 'RSSNOM', 'RSSMED', 'ACTMED')
        ORDER by data_num  ");

    $ok = TRUE;
    while ($ok == TRUE) {
        $ok = FALSE;
        $record = pg_fetch_array($result);
        if ($record != FALSE) {
            $ok = TRUE;
            $data_type = trim($record["data_type"]);
            $data = $record["data"];

            if ($data_type == "MED") {
                $handle = fopen($file_MED, 'a');
                fwrite($handle, uncompress(pg_unescape_bytea($data)));
                fclose($handle);
            }
            
            if ($data_type == "RSSMED") {
                $handle = fopen($file_RSSMED, 'a');
                fwrite($handle, uncompress(pg_unescape_bytea($data)));
                fclose($handle);
            }
            
            if ($data_type == "RSSNOM") {
                $handle = fopen($file_RSSNOM, 'a');
                fwrite($handle, uncompress(pg_unescape_bytea($data)));
                fclose($handle);
            }
            
            if ($data_type == "ACTMED") {
                $handle = fopen($file_ACTMED, 'a');
                fwrite($handle, uncompress(pg_unescape_bytea($data)));
                fclose($handle);
            }
            
        }
    }
    
    $file_exists_MED = false;
    $file_exists_RSSMED = false;
    $file_exists_RSSNOM = false;
    $file_exists_ACTMED = false;
    

    if (file_exists($file_MED)) {
        logInfoMsg("Fichier Médecins restauré");
        $file_exists_MED = true;
    }
    if (file_exists($file_RSSMED)) {
        logInfoMsg("Fichier correspondance RSS - Médecins restauré");
        $file_exists_RSSMED = true;
    }
    if (file_exists($file_RSSNOM)) {
        logInfoMsg("Fichier correspondance RSS - Noms restauré");
        $file_exists_RSSNOM = true;
    }
    if (file_exists($file_ACTMED)) {
        logInfoMsg("Fichier correspondance Actes - Médecins restauré");
        $file_exists_ACTMED = true;
    }
    
    
    
    logInfoMsg("FIN RESTAURATION DONNEES COMPLEMENTAIRES");
    
}

function suppression_fichiers() {


    global $file_MED;
    global $file_RSSMED;
    global $file_RSSNOM;
    global $file_ACTMED;
    global $file_RSS;
    global $file_RSF;
    global $file_FCP;
    global $file_ANO;
    global $file_RSA;
    global $file_CTL;
    global $file_TRA;
    global $file_LEG;
    global $file_VSJ;
    global $file_VSE;
    global $file_IUM;
    global $file_PIE;
    global $file_VAL;
    global $file_PORG;
    global $file_DIAP;
    global $file_COMPLOG;
    global $file_TSP;

    logInfoMsg("SUPPRESSION FICHIERS DE TRAVAIL");
    
    
    @unlink($file_RSS);
    @unlink($file_RSF);
    @unlink($file_FCP);
    @unlink($file_ANO);
    @unlink($file_RSA);
    @unlink($file_CTL);
    @unlink($file_TRA);
    @unlink($file_LEG);
    @unlink($file_MED);
    @unlink($file_RSSMED);
    @unlink($file_RSSNOM);
    @unlink($file_ACTMED);
    @unlink($file_COMPLOG);
    @unlink($file_IUM);
    @unlink($file_PIE);
    @unlink($file_VAL);
    @unlink($file_PORG);
    @unlink($file_DIAP);
    @unlink($file_VSJ);
    @unlink($file_VSE);
    @unlink($file_TSP);

    
    logInfoMsg("FIN FICHIERS DE TRAVAIL");
    
}


function temp_file() {
    $temp_file = tempnam("../../../temp/", "PMSI");
    file_put_contents($temp_file, "");
    return $temp_file;
}


function generation_initialisation() {

    global $iCTI_connexion;
    
    global $import_id;

    global $annee_fin;
    global $annee_mois_fin;
    
    global $file_RSS;

    logInfoMsg("INITIALISATION GENERATION");
    
    $nb = 0;
    $nbW = 0;
    $nbW = 0;
    $nbE = 0;

    begin_trans();
    
    $sqlcmd = "UPDATE pmsi.p_imports SET ";
    $sqlcmd = $sqlcmd . "etat_en_cours = 'G' ";
    $sqlcmd = $sqlcmd . "WHERE oid = $import_id";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );

    
    // Période RSS
    $result = $iCTI_connexion->query("select date_debut, date_fin FROM pmsi.p_imports WHERE oid = $import_id");
    $record = pg_fetch_array($result);
    if ($record != FALSE) {
        $date_debut = $record["date_debut"];
        $date_fin = $record["date_fin"];
    }

    $annee_fin = substr($date_fin , 0 , 4);
    $annee_mois_fin = date('Ym', strtotime($date_fin));
    
    logInfoMsg("Période de sortie du $date_debut au $date_fin");
    
    
    logInfoMsg("Tables de travail");
    
    $sqlcmd = "DROP TABLE IF EXISTS temp.p_identites;
            SELECT base.cti_create_table_from('temp', 'p_identites', 'pmsi', '');
            CREATE INDEX i_identites_1 ON temp.p_identites USING btree (rss_id);
            CREATE INDEX i_identites_2 ON temp.p_identites USING btree (no_rss);";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
    
    $sqlcmd = "DROP TABLE IF EXISTS temp.p_rss;
            SELECT base.cti_create_table_from('temp', 'p_rss', 'pmsi', '');
            CREATE INDEX i_rss_1 ON temp.p_rss USING btree (oid);
            CREATE INDEX i_rss_2 ON temp.p_rss USING btree (no_rss);
            CREATE INDEX i_rss_3 ON temp.p_rss USING btree (no_sejour_administratif);
            CREATE INDEX i_rss_4 ON temp.p_rss USING btree (ghm_id);";
            
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
    
    $sqlcmd = "DROP TABLE IF EXISTS temp.p_rss_rum;
            SELECT base.cti_create_table_from('temp', 'p_rss_rum', 'pmsi', '');
            CREATE INDEX i_rss_rum_1 ON temp.p_rss_rum USING btree (rss_id);
            CREATE INDEX i_rss_rum_2 ON temp.p_rss_rum USING btree (no_rss);";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
        
    $sqlcmd = "DROP TABLE IF EXISTS temp.p_rss_actes;
            SELECT base.cti_create_table_from('temp', 'p_rss_actes', 'pmsi', '');
            CREATE INDEX i_rss_actes_1 ON temp.p_rss_actes USING btree (rss_id);
            CREATE INDEX i_rss_actes_2 ON temp.p_rss_actes USING btree (acte_id);
            CREATE INDEX i_rss_actes_3 ON temp.p_rss_actes USING btree (medecin_id);
            CREATE INDEX i_rss_actes_4 ON temp.p_rss_actes USING btree (no_rss);";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
        
    $sqlcmd = "DROP TABLE IF EXISTS temp.p_rss_diagnostics;
            SELECT base.cti_create_table_from('temp', 'p_rss_diagnostics', 'pmsi', '');
            CREATE INDEX i_rss_diagnostics_1 ON temp.p_rss_diagnostics USING btree (rss_id);
            CREATE INDEX i_rss_diagnostics_2 ON temp.p_rss_diagnostics USING btree (diagnostic_id);
            CREATE INDEX i_rss_diagnostics_3 ON temp.p_rss_diagnostics USING btree (no_rss);";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
    
    $sqlcmd = "DROP TABLE IF EXISTS temp.p_rss_lpp;
            SELECT base.cti_create_table_from('temp', 'p_rss_lpp', 'pmsi', '');
            CREATE INDEX i_rss_lpp_1 ON temp.p_rss_lpp USING btree (rss_id);
            CREATE INDEX i_rss_lpp_2 ON temp.p_rss_lpp USING btree (no_rss);";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_lpp );
    commit_trans();
    
    $sqlcmd = "DROP TABLE IF EXISTS temp.p_rss_ucd;
            SELECT base.cti_create_table_from('temp', 'p_rss_ucd', 'pmsi', '');
            CREATE INDEX i_rss_ucd_1 ON temp.p_rss_ucd USING btree (rss_id);
            CREATE INDEX i_rss_ucd_2 ON temp.p_rss_ucd USING btree (no_rss);";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_ucd );
    commit_trans();
    
    $sqlcmd = "DROP TABLE IF EXISTS temp.p_rss_leg;
            SELECT base.cti_create_table_from('temp', 'p_rss_leg', 'pmsi', '');
            CREATE INDEX i_rss_leg_1 ON temp.p_rss_leg USING btree (rss_id);";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_leg );
    commit_trans();
    
    $sqlcmd = "DROP TABLE IF EXISTS temp.p_rss_maternite;
            SELECT base.cti_create_table_from('temp', 'p_rss_maternite', 'pmsi', '');
            CREATE INDEX i_rss_maternite_1 ON temp.p_rss_maternite USING btree (rss_id);";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
    
    $sqlcmd = "DROP TABLE IF EXISTS temp.p_ctl_mt2a;
            SELECT base.cti_create_table_from('temp', 'p_ctl_mt2a', 'pmsi', '');
            CREATE INDEX i_ctl_mt2a_1 ON temp.p_ctl_mt2a USING btree (rss_id);
            CREATE INDEX i_ctl_mt2a_2 ON temp.p_ctl_mt2a USING btree (no_rss);";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_leg );
    commit_trans();
    
    $sqlcmd = "DROP TABLE IF EXISTS temp.p_vidhosp;
            SELECT base.cti_create_table_from('temp', 'p_vidhosp', 'pmsi', '');
            CREATE INDEX i_vidhosp_1 ON temp.p_vidhosp USING btree (rss_id);";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_leg );
    commit_trans();
    
    $sqlcmd = "DROP TABLE IF EXISTS temp.p_vidhosp_crc;
            SELECT base.cti_create_table_from('temp', 'p_vidhosp_crc', 'pmsi', '');
            CREATE INDEX i_vidhosp_crc_1 ON temp.p_vidhosp_crc USING btree (rss_id);";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_leg );
    commit_trans();

    $sqlcmd = "DROP TABLE IF EXISTS temp.p_vidhosp_dmt;
            SELECT base.cti_create_table_from('temp', 'p_vidhosp_dmt', 'pmsi', '');
            CREATE INDEX i_vidhosp_dmt_1 ON temp.p_vidhosp_dmt USING btree (rss_id);";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_leg );
    commit_trans();

		$sqlcmd = "DROP TABLE IF EXISTS temp.p_vidhosp_dmt_crc;
            SELECT base.cti_create_table_from('temp', 'p_vidhosp_dmt_crc', 'pmsi', '');
            CREATE INDEX i_vidhosp_dmt_crc_1 ON temp.p_vidhosp_dmt_crc USING btree (rss_id);";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_leg );
    commit_trans();
    
    $sqlcmd = "DROP TABLE IF EXISTS temp.p_rsa;
            SELECT base.cti_create_table_from('temp', 'p_rsa', 'pmsi', '');
            CREATE INDEX i_rsa_1 ON temp.p_rsa USING btree (rss_id);
            CREATE INDEX i_rsa_2 ON temp.p_rsa USING btree (no_rss);";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_leg );
    commit_trans();
    
    $sqlcmd = "DROP TABLE IF EXISTS temp.p_rsa_rdth;
            SELECT base.cti_create_table_from('temp', 'p_rsa_rdth', 'pmsi', '');
            CREATE INDEX i_rsa_rdth_1 ON temp.p_rsa_rdth USING btree (rss_id);
            CREATE INDEX i_rsa_rdth_2 ON temp.p_rsa_rdth USING btree (ghs_id);";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_leg );
    commit_trans();
            
    $sqlcmd = "DROP TABLE IF EXISTS temp.p_rsf_total;
            SELECT base.cti_create_table_from('temp', 'p_rsf_total', 'pmsi', '');
            CREATE INDEX i_rsf_total_1 ON temp.p_rsf_total USING btree (rss_id);
            CREATE INDEX i_rsf_total_2 ON temp.p_rsf_total USING btree (no_rss)";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
    
    $sqlcmd = "DROP TABLE IF EXISTS temp.p_rsf_detail;
            SELECT base.cti_create_table_from('temp', 'p_rsf_detail', 'pmsi', '');
            CREATE INDEX i_rsf_detail_1 ON temp.p_rsf_detail USING btree (rss_id);
            CREATE INDEX i_rsf_detail_2 ON temp.p_rsf_detail USING btree (prestation_id);
            CREATE INDEX i_rsf_detail_3 ON temp.p_rsf_detail USING btree (no_rss);";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();

    $sqlcmd = "DROP TABLE IF EXISTS temp.p_rsf_detail_non_valorise;
            SELECT base.cti_create_table_from('temp', 'p_rsf_detail_non_valorise', 'pmsi', '');";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
	
	$sqlcmd = "DROP TABLE IF EXISTS temp.p_rss_transferts;
            SELECT base.cti_create_table_from('temp', 'p_rss_transferts', 'pmsi', '');
            CREATE INDEX i_rss_transferts_1 ON temp.p_rss_transferts USING btree (rss_id);";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_lpp );
    commit_trans();

    // Creation table temp avec no_rss pour recuperer les etablissement de provenances
    $sqlcmd = "DROP TABLE IF EXISTS temp.transferts_with_no_rss;
               CREATE TABLE temp.transferts_with_no_rss AS (
                    SELECT no_rss, etablissement_destination_id, etablissement_provenance_id 
                    FROM pmsi.p_rss_transferts
                    JOIN pmsi.p_rss ON p_rss.oid = rss_id
                    WHERE date_sortie >= '$date_debut'
               );";
    $toResult = execute_sql($sqlcmd);  
    commit_trans();


	$sqlcmd = "DROP TABLE IF EXISTS temp.p_fichsup_transports;
            SELECT base.cti_create_table_from('temp', 'p_fichsup_transports', 'pmsi', '');";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_lpp );
    commit_trans();

    logInfoMsg("Suppression génération précédente");
    



    // Suppression gégération précédente
    $sqlcmd = "DELETE FROM pmsi.p_rss WHERE import_id = $import_id ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
    
    nettoyer_sejours();
    
    $sqlcmd = "DELETE FROM pmsi.p_fichsup_transports WHERE import_id = $import_id";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
    
    
    logInfoMsg("Pointage période");
    
    $date_debut_delete = $date_debut;
    if (substr($date_fin,0,4) != substr($date_debut,0,4)) {
        $date_debut_delete = substr($date_fin,0,4) . "-01-01";
    }

    $sqlcmd = <<<SQL
            UPDATE pmsi.p_rss set etat = 'S' 
        WHERE date_trunc('month', date_sortie) >= date_trunc('month', '$date_debut_delete'::date) 
        AND date_trunc('month', date_sortie) <= date_trunc('month', '$date_fin'::date)
SQL;


    execute_sql($sqlcmd, $nbE, $nbW_rum );
    
    
    commit_trans();
    
    if (substr($date_fin,0,4) != substr($date_debut,0,4)) {
    
        enable_index("i_rss_1");
        
    
        // Pointage des dossiers hors période
        $dates_array = array();
        $handle = @fopen($file_RSS, "r");
        if ($handle) {
            while (!feof($handle)) {
                $buffer = fgets($handle, 99999);
                
                $no_ligne++;
                if (trim($buffer) != "" && $no_ligne < 100000000000) {
                    $nb++;
                    
                    $BUF_record = read_rum_partial_line($buffer);
                    
                    if ($BUF_record["type_enregistrement"] == "RUM") {

                        $no_rss = get_numrss($BUF_record["no_rss"]);
                        $rss_ok = TRUE;
                        if ($rss_ok == TRUE) {
                            if (! controle_check_date($BUF_record["date_sortie"],$erreur,$commentaire)) {
                            }
                            else {
                                $dates_array[$no_rss] = get_date_AAAAMMJJ($BUF_record["date_sortie"]);
                            }
                        }
                    }
                    
                }
                
            }
            
        }
        @fclose($handle);
        
        foreach ( array_keys($dates_array) as $no_rss ) {
            $date_sortie_rss = "";
            $date_sortie_rss = @$dates_array[$no_rss];
            if (substr($date_fin,0,4) != substr($date_sortie_rss,0,4)) {
                $sqlcmd = "UPDATE pmsi.p_rss set etat = 'S' 
                    WHERE date_trunc('month', date_sortie) >= date_trunc('month', '$date_debut'::date) 
                    AND date_trunc('month', date_sortie) <= date_trunc('month', '$date_fin'::date)
                    AND no_rss = $no_rss";
                $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );

                logWarnMsg("Le RSS $no_rss (sorti le $date_sortie_rss) est hors période");
            }
        }
    
        disable_index("i_rss_1");
    
    }
    
    commit_trans();
    
    logInfoMsg("FIN INITIALISATION GENERATION. $nbE erreurs.");
    
}



function generation_initialisation_parametres() {
    
    global $ENDSTATUS;
    global $iCTI_connexion;
    
    logInfoMsg("INITIALISATION PARAMETRES");
    
    $nbW = 0;
    $nbE = 0;
    
    begin_trans();
    
    // Lance la fonction qui insère l'oid 0 dans les tables de paramètres utlisées par le module PMSI
    $sqlcmd = " SELECT pmsi.cti_initialize_tables();";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    
    commit_trans();
    
    logInfoMsg("FIN INITIALISATION PARAMETRES. $nbE erreurs.");
}


function generation_med() {

    global $iCTI_connexion;
    global $file_MED;
    global $file_exists_MED;

    $nb = 0;
    $nbW = 0;
    $nbE = 0;

    if ($file_exists_MED) {

    logInfoMsg("GENERATION DES MEDECINS");

    begin_trans();

    commit_trans();
    
    $no_ligne = 0;
    


    // Depuis le fichier
    $handle = @fopen($file_MED, "r");
    if ($handle) {
        while (!feof($handle)) {
            $buffer = fgets($handle, 99999);
            
            $no_ligne++;
            if (trim($buffer) != "" && $no_ligne < 100000000000 ) {
            
                $nb++;
                
                $BUF_record = read_med_line($buffer);

                $code = toSQL($BUF_record["code"]);
                $nom = toSQL($BUF_record["nom"]);
                if ($prenom != "*CMM") {
                    $prenom = toSQL($BUF_record["prenom"]);
                    $specialite_id = get_specialite_medecin($BUF_record["specialite"]);
                    $specialite_interne_id = 0;
                    $no_adeli = toSQL($BUF_record["no_adeli"]);
                    $statut = "";

                    
                    $new_med = TRUE;
                    $result = $iCTI_connexion->query("select oid FROM pmsi.t_medecins WHERE code = '$code'");
                    $ok = TRUE;
                    while ($ok == TRUE) {
                        $ok = FALSE;
                        $record = pg_fetch_array($result);
                        if ($record != FALSE) {
                            $new_med = FALSE;
                        }
                    }
                    
                    if ($new_med == TRUE) {
                        $sqlcmd = "INSERT INTO pmsi.t_medecins( ";
                        $sqlcmd = $sqlcmd . "code, ";
                        $sqlcmd = $sqlcmd . "nom, ";
                        $sqlcmd = $sqlcmd . "prenom, ";
                        $sqlcmd = $sqlcmd . "specialite_id, ";
                        $sqlcmd = $sqlcmd . "specialite_interne_id, ";
                        $sqlcmd = $sqlcmd . "no_adeli, ";
                        $sqlcmd = $sqlcmd . "statut ";
                        $sqlcmd = $sqlcmd . ") ";
                        $sqlcmd = $sqlcmd . "VALUES( ";
                        $sqlcmd = $sqlcmd . "'$code', ";
                        $sqlcmd = $sqlcmd . "'$nom', ";
                        $sqlcmd = $sqlcmd . "'$prenom', ";
                        $sqlcmd = $sqlcmd . "$specialite_id, ";
                        $sqlcmd = $sqlcmd . "$specialite_interne_id, ";
                        $sqlcmd = $sqlcmd . "'$no_adeli', ";
                        $sqlcmd = $sqlcmd . "'$statut' ";
                        $sqlcmd = $sqlcmd . ") ";
                        $toResult = execute_sql($sqlcmd, $nbE, $nbW );
                    }
                    else {
                        $sqlcmd = "UPDATE pmsi.t_medecins SET nom = '$nom', prenom = '$prenom'  
                                    WHERE code = '$code' AND code = nom;
                                    UPDATE pmsi.t_medecins SET specialite_id = $specialite_id
                                    WHERE code = '$code' 
                                ";
                        $toResult = execute_sql($sqlcmd, $nbE, $nbW );
                        
                        
                    }
                }
                else {

                    
                    $new_med = TRUE;
                    $result = $iCTI_connexion->query("select oid FROM pmsi.t_comites_medicaux WHERE code = '$code'");
                    $ok = TRUE;
                    while ($ok == TRUE) {
                        $ok = FALSE;
                        $record = pg_fetch_array($result);
                        if ($record != FALSE) {
                            $new_med = FALSE;
                        }
                    }
                    
                    if ($new_med == TRUE) {
                        $sqlcmd = "INSERT INTO pmsi.t_comites_medicaux( ";
                        $sqlcmd = $sqlcmd . "code, ";
                        $sqlcmd = $sqlcmd . "texte ";
                        $sqlcmd = $sqlcmd . ") ";
                        $sqlcmd = $sqlcmd . "VALUES( ";
                        $sqlcmd = $sqlcmd . "'$code', ";
                        $sqlcmd = $sqlcmd . "'$texte' ";
                        $sqlcmd = $sqlcmd . ") ";
                        $toResult = execute_sql($sqlcmd, $nbE, $nbW );
                    }
                    else {
                        $sqlcmd = "UPDATE pmsi.t_comites_medicaux SET texte = '$nom'  ";
                        $sqlcmd = $sqlcmd . "WHERE code = '$code' AND texte <> '$nom' ";
                        $toResult = execute_sql($sqlcmd, $nbE, $nbW );
                    }
                
                }
                

            }
        
        }
        
        fclose($handle);
    
    }
    
    commit_trans();
    }
    // Spécialités internes
    $sqlcmd = "INSERT INTO pmsi.t_specialites_internes_medecin (code, texte) ";
    $sqlcmd = $sqlcmd . "SELECT code || '..', texte  ";
    $sqlcmd = $sqlcmd . "FROM pmsi.t_specialites_medecin  ";
    $sqlcmd = $sqlcmd . "WHERE oid > 0 AND length(code) = 2 AND code NOT LIKE '%..%' ";
    $sqlcmd = $sqlcmd . "AND code || '..' NOT IN (SELECT code FROM pmsi.t_specialites_internes_medecin); ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbWWW );
    commit_trans();

    $sqlcmd = "UPDATE pmsi.t_medecins  ";
    $sqlcmd = $sqlcmd . "SET specialite_interne_id = t_specialites_internes_medecin.oid ";
    $sqlcmd = $sqlcmd . "FROM pmsi.t_specialites_medecin, pmsi.t_specialites_internes_medecin ";
    $sqlcmd = $sqlcmd . "WHERE t_medecins.specialite_interne_id = 0 ";
    $sqlcmd = $sqlcmd . "AND t_medecins.specialite_id <> 0 ";
    $sqlcmd = $sqlcmd . "AND t_medecins.specialite_id = t_specialites_medecin.oid ";
    $sqlcmd = $sqlcmd . "AND t_specialites_medecin.code || '..' = t_specialites_internes_medecin.code ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbWWW );
    commit_trans();
    
    
    analyse_table("t_medecins");
    
    
    logInfoMsg("FIN GENERATION DES MEDECINS. $nb lus, $nbW écrits, $nbE erreurs.");

    
}



// Traitement des RUM
function generation_rum() {

    
    global $iCTI_connexion;
    global $ENV_TYPEETS;
    
    global $import_id;

    
    global $file_RSSMED;
    global $file_RSSNOM;
    global $file_ACTMED;
    global $file_RSS;
    global $file_RSF;

    global $file_exists_RSF;
    
    global $rssmed_array;
    global $rssnom_array;
    global $rssprenom_array;
    
    global $current_rsfa_index;
    

    logInfoMsg("GENERATION DES RUM");

    
    begin_trans();
    
    $nb = 0;
    $nbW = 0;
    $nbW_rss = 0;
    $nbW_rum = 0;
    $nbW_diags = 0;
    $nbW_actes = 0;
    $nbW = 0;
    $nbE = 0;

    commit_trans();
    

    
    // recherche des RSS dans les RSF
    $rsss_array = array();
    $prestations_principales_array = array();
    $ghss_rss_array = array();
    $ghss_rssbb_array = array();
    $ghss_rssdia_array = array();

    if ($file_exists_RSF) {
        logInfoMsg("Extraction RSS dans RSF");
        
        $current_rsfa_index = 0;
        
        $ghs_prestation_id = get_prestation("GHS");
        
        $handle = @fopen($file_RSF, "r");
        if ($handle) {
            while (!feof($handle)) {
                $buffer = fgets($handle, 99999);
                
                if (trim($buffer) != "" ) {

                    $BUF_record = read_rsf_partial_line($buffer);
                    
                    if ($BUF_record["ok"] == TRUE) {

                        // ENTETE RSF
                        if ($BUF_record["type_enregistrement"] == "A") {
                        
                            
                            
                            // RSS
                            if (controle_check_num($BUF_record["no_rss"],0,FALSE,$erreur,$commentaire)) {
                                $no_rss = get_numrss($BUF_record["no_rss"]);
                                $rsss_array[$no_rss] = "OK";
                                //$prestations_principales_array[$no_rss] = 0;
                                //$ghss_rss_array[$no_rss] = 0;
                            }
                            
                        }
                        
                        // prestation principale  GHS
                        if ($BUF_record["type_enregistrement"] == "B") {
                            
                            // RSS
                            if ($BUF_record["code_acte"] == "GHS") {
                                $no_rss = get_numrss($BUF_record["no_rss"]);
                                $prestations_principales_array[$no_rss] = $ghs_prestation_id;
                                $ghs_id = get_ghs($BUF_record["no_ghs"]);
                                $ghs_code_num = get_num($BUF_record["no_ghs"]);
                                if ($ghs_code_num < 5800 || $ghs_code_num > 5940) {
                                    if ($ghs_code_num != 9604 && $ghs_code_num != 9605) {
                                        $ghss_rss_array[$no_rss] = $ghs_id;
                                    }
                                    else {
                                        $ghss_rssdia_array[$no_rss] = $ghs_id;
                                    }
                                }
                                else {
                                    $ghss_rssbb_array[$no_rss] = $ghs_id;
                                }
                            }
                            
                        }
                        
                    }
                    
                }
                
            }
            
        }
    }
    

    
    // Medecins par RSS
    $rssmed_array = array();
    $rsscmm_array = array();
    $handle = @fopen($file_RSSMED, "r");
    if ($handle) {
        while (!feof($handle)) {
            $buffer = fgets($handle, 99999);
            
            $no_ligne++;
            if (trim($buffer) != "" && $no_ligne < 100000000000 ) {
                $BUF_record = read_rssmed_line($buffer);
                $no_rss = get_numrss($BUF_record["no_rss"]);
                if ($BUF_record["is_comite"] != "1") {
                    $rssmed_array[$no_rss] = $BUF_record["code_medecin"];
                }
                else {
                    $rsscmm_array[$no_rss] = $BUF_record["code_medecin"];
                }
            }
        }
        fclose($handle);
    
    }

    
    // Noms des RSS
    $rssnom_array = array();
    $rssprenom_array = array();
    $rssnopatient_array = array();

    $handle = @fopen($file_RSSNOM, "r");
    if ($handle) {
        while (!feof($handle)) {
            $buffer = fgets($handle, 99999);
            if (trim($buffer) != "" ) {
                $BUF_record = read_rssnom_line($buffer);
                $no_rss = get_num($BUF_record["no_rss"] );
                $rssnom_array[$no_rss] = $BUF_record["nom"];
                $rssprenom_array[$no_rss] = $BUF_record["prenom"];
                $rssnopatient_array[$no_rss] = $BUF_record["no_patient"];
            }
        }
        fclose($handle);
    }
    
    
    // Exécutants
    if (! $file_exists_RSF || $ENV_TYPEETS != "1") {
        $actmed_array = array();

        $handle = @fopen($file_ACTMED, "r");
        if ($handle) {
            while (!feof($handle)) {
                $buffer = fgets($handle, 99999);
                
                if (trim($buffer) != "" ) {

                    $BUF_record = read_actmed_line($buffer);
                    
                    if ($BUF_record["type_enregistrement"] == "ACTMED") {
                    
                        $cle = get_numrss($BUF_record["no_rss"]) . $BUF_record["code_acte"] . get_date_AAAAMMJJ($BUF_record["date_acte"]) . $BUF_record["activite_ccam"] ;
                        $actmed_array[$cle] = $BUF_record["code_medecin"];
                        
                        $cle = get_numrss($BUF_record["no_rss"]) . $BUF_record["code_acte"] . "00000000" . $BUF_record["activite_ccam"];
                        $actmed_array[$cle] = $BUF_record["code_medecin"];
                        
                        // cas particulier actes anesthésie en activite 1
                        if ($BUF_record["activite_ccam"] == "4") {
                            $acte_anesthesie = array("AFLB010", "GELE001", "YYYY003", "YYYY004", "YYYY015", "YYYY020", "YYYY041", "YYYY044", "YYYY108", "YYYY118", "ZZLP008", "ZZLP012", "ZZLP025", "ZZLP030", "ZZLP042", "ZZLP054");
                                
                            if (in_array($BUF_record["code_acte"], $acte_anesthesie)){
                                $cle = get_numrss($BUF_record["no_rss"]) . $BUF_record["code_acte"] . get_date_AAAAMMJJ($BUF_record["date_acte"]) . "1";
                                $actmed_array[$cle] = $BUF_record["code_medecin"];
                                
                                $cle = get_numrss($BUF_record["no_rss"]) . $BUF_record["code_acte"] . "00000000" . "1";
                                $actmed_array[$cle] = $BUF_record["code_medecin"];
                            }
                        }

                    }
                
                }
            
            }
            
            fclose($handle);
        
        }
    }
    
    logInfoMsg("Génération RSS et RUM");

    
    $no_ligne = 0;
    
    $sqlcmd_insert_rum = "INSERT INTO temp.p_rss_rum(
        rss_id,
        finess,
        no_rss,
        no_rum,
        date_entree,
        date_sortie,
        mode_entree,
        provenance,
        mode_sortie,
        destination,
        passage_urgences_code,
        duree_sejour,
        nb_seances,
        unite_medicale,
        diagnostic_principal_id,
        diagnostic_relie_id,
        unite_medicale_id,
        type_autorisation,
        igs2,
        type_autorisation_lit_dedie,
        conversion_hp_hc_id
    )";
    
    $sqlcmd_insert_rss = "INSERT INTO temp.p_rss(
        oid,
        no_patient,
        finess,
        no_rss,
        version_groupage,
        code_retour_groupage,
        date_naissance,
        sexe,
        date_entree,
        date_sortie,
        mode_entree,
        provenance,
        mode_sortie,
        destination,
        passage_urgences_code,
        code_postal,
        code_postal_id,
        poids_bebe,
        igs2,
        cma,
        groupe_ghm,
        duree_sejour,
        nb_rsa,
        age,
        supprime,
        date_import,
        nb_rum,
        secteur,
        no_sejour_administratif,
        nb_seances,
        ghm_fg9,
        ghm_id,
        medecin_rss_id,
        comite_medical_id,
        ghs_id,
        mois_sortie,
        diagnostic_principal_id,
        diagnostic_relie_id,
        no_rum_principal,
        unite_medicale_principale_id,
        prestation_principale_id,
        import_id,
        en_cours,
        en_cours_etat,
        traitement_epmsi,
        age_gestationnel,
        date_dernieres_regles,
        confirmation_codage,
        type_machine_rdth,
        type_dosimetrie,
        numero_innovation,
        nombre_ivg_anterieures,
        annee_ivg_precedente,
        nombre_naissances_vivantes_anterieures,
        coefficient_prudentiel_theorique,
        conversion_hp_hc_id,
        raac_id,
        rescrit_tarif_id,
        adm_prod_reshospi_id,
        contexte_pat_id,
        nb_intervention_id,
        np_id
    )";
    
    $sqlcmd_insert_identite = "INSERT INTO temp.p_identites(
        rss_id,
        finess,
        no_rss,
        nom,
        prenom
    )";
    
    $sqlcmd_insert_diagnostic = "INSERT INTO temp.p_rss_diagnostics(
        rss_id,
        finess,
        no_rss,
        no_rum,
        diagnostic_id,
        type_diagnostic,
        type_diagnostic_rss,
        imprecis,
        unite_medicale,
        unite_medicale_id
    )";
    
    $sqlcmd_insert_acte = "INSERT INTO temp.p_rss_actes(
        rss_id,
        finess,
        no_rss,
        no_rum,
        unite_medicale,
        unite_medicale_id,
        date_acte,
        medecin_id,
        acte_id,
		acte_ccam_descriptif_id,
        nombre,
        phase_ccam,
        activite_ccam,
        extension_ccam,
        modificateur_ccam_1,
        modificateur_ccam_2,
        modificateur_ccam_3,
        modificateur_ccam_4,
        remboursement_excp_ccam,
        association_nonprevue_ccam
    )";
    
    $sequence_rss_id = 0;
    $sqlcmd_exec = "";
    
    $handle = @fopen($file_RSS, "r");
    if ($handle) {
        while (!feof($handle)) {
            $buffer = fgets($handle, 99999);
            
            $no_ligne++;
            if (trim($buffer) != "" && $no_ligne < 100000000000 ) {
            
                $nb++;
                
                $BUF_record = read_rum_line($buffer);
                
                $no_rss = get_numrss($BUF_record["no_rss"]);
                $rss_ok = TRUE;

                if ($rss_ok == TRUE) {
                
                    if (strlen($sqlcmd_exec) > 64000) {
                        $toResult = execute_sql($sqlcmd_exec, $nbE, $nbW_actesxx );
                        $sqlcmd_exec = "";
                    }

                    if ($BUF_record["type_enregistrement"] == "RUM") {
                    
                        $no_patient = 0;
                        $finess = $BUF_record["finess"];
                        $no_rss = get_numrss($BUF_record["no_rss"]);
                        
                        $en_cours = "0";
                        $en_cours_etat = "";
                        
                        $version_groupage = $BUF_record["version_groupage"];
                        $code_retour_groupage = $BUF_record["groupage_retour"];
                        //$date_naissance = sqlDate($BUF_record["date_naissance"]);
                        if (controle_check_date($BUF_record["date_naissance"],$none,$none, true)) {
                            $date_naissance = sqlDate($BUF_record["date_naissance"]);
                        }
                        else {
                            $date_naissance = default_birth_date($BUF_record["date_naissance"]);
                        }
                        $sexe = $BUF_record["sexe"];
                        $date_entree = sqlDate($BUF_record["date_entree"]);
                        $mode_entree = get_mode_entree($BUF_record["mode_entree"]);
                        $provenance = get_provenance($BUF_record["provenance"]);
                        $date_sortie = sqlDate($BUF_record["date_sortie"]);
                        $mode_sortie = get_mode_sortie($BUF_record["mode_sortie"]);
                        $destination = get_destination($BUF_record["destination"]);
                        $passage_urgences = $BUF_record["passage_urgences"];
                        $code_postal = $BUF_record["code_postal"];
                        $poids_bebe = get_num($BUF_record["poids_bebe"]);
                        $age_gestationnel = get_num($BUF_record["age_gestationnel"]);
                        if(controle_check_date($BUF_record["date_dernieres_regles"],$none,$none)){
                            $date_dernieres_regles = sqlDate($BUF_record["date_dernieres_regles"]);
                        }else{
                            $date_dernieres_regles = "2099-12-31";
                        }
                        $confirmation_codage = $BUF_record["confirmation_codage"];
                        $type_machine_rdth = $BUF_record["type_machine_rdth"];
                        $type_dosimetrie = $BUF_record["type_dosimetrie"];
                        $numero_innovation = $BUF_record["numero_innovation"];
                        $nombre_ivg_anterieures = get_num($BUF_record["nombre_ivg_anterieures"]);
                        $annee_ivg_precedente = get_num($BUF_record["annee_ivg_precedente"]);
                        $nombre_naissances_vivantes_anterieures = get_num($BUF_record["nombre_naissances_vivantes_anterieures"]);
                        $code_postal = $BUF_record["code_postal"];
                        $igs2 = get_num($BUF_record["igs2"]);
                        $cma = "";
                        $groupe_ghm = "";
                        // $duree_sejour = 0;       // Remplacé le 02/05/2013 par CLA
                        // La duree de séjour du rum est la différence entre les dates de sortie et d'entrée
                        $duree_sejour = (strtotime($date_sortie) - strtotime($date_entree)) / ( 60 * 60 * 24);
                        $nb_rsa = 1;
                        $age = 0;
                        $supprime = "";
                        $date_import = "2099-12-31";
                        $nb_rum = 1;
                        $secteur = "";
                        $no_sejour_administratif = get_charAsNum($BUF_record["no_sejour_administratif"]);
                        $type_autorisation_lit_dedie = $BUF_record["type_autorisation_lit"];
                        $nb_seances = get_num($BUF_record["nombre_seances"]);
                        if ($nb_seances == 0 && substr($BUF_record["ghm"], 0 , 2) == "28") {
                            $nb_seances = 1;
                        }
                        if ($nb_seances > 1 && substr($BUF_record["ghm"], 0 , 2) == "28") {
                            $nb_rsa = $nb_seances;
                        }
                        $conversion_hp_hc_id = get_conversion_hp_hc($BUF_record["conversion_hp_hc"]);
                        $raac_id = get_raac($BUF_record["raac"]);
                        $contexte_pat_id = get_contexte_pat($BUF_record["contexte_particulier"]);
                        $adm_prod_reshospi_id = get_adm_prod_reshospi($BUF_record["administration_prod_rh"]);
                        $rescrit_tarif_id = get_rescrit_tarif($BUF_record["rescrit_tarifaire"]);
                        $nb_interventions_id = get_nb_interventions($BUF_record["categorie_nb_interventions"]);
                        $ghm_fg9 = "";
                        $ghm_id = 0;
                        $medecin_rss_id = 0;
                        $comite_medical_id = 0;
                        $ghs_id = 0;
                        $mois_sortie = 0;
                        $diagnostic_principal_id = 0;
                        $diagnostic_relie_id = 0;
                        $no_rum_principal = 1;
                        $unite_medicale_principale_id = 0;
                        $np = get_np($BUF_record["np"]);
                        
                        $in_rsf = "";
                        if ($ENV_TYPEETS == "1") {
                            $in_rsf = @$rsss_array[$no_rss];
                        }
                        else {
                            $in_rsf = "OK";
                        }
                        if ($in_rsf == "OK") {
                            
                            $ghm_id = get_ghm($BUF_record["ghm"]);
                            $diagnostic_principal_id = get_diagnostic($BUF_record["diagnostic_principal"]);

                            
                            if ($BUF_record["diagnostic_relie"] != "") {
                                $diagnostic_relie_id = get_diagnostic($BUF_record["diagnostic_relie"]);
                            }
                            
                            // Medecin RSS
                            $code_med = "";
                            $code_med = @$rssmed_array[get_numrss($BUF_record["no_rss"])];
                            if ($code_med != "") {
                                $medecin_rss_id = get_medecin($code_med);
                            }
                            
                            // Comité médical
                            
                            $code_cmm = "";
                            $code_cmm = @$rsscmm_array[get_numrss($BUF_record["no_rss"])];
                            if ($code_cmm != "") {
                                $comite_medical_id = get_comite_medical($code_cmm);
                            }
                            
                            
                            // OID rss
                            
                            $no_rum = get_num($BUF_record["no_rum"]);
                            
                            if ($no_rum == 1) {
                                $rss_id = 0;
                                if ($sequence_rss_id == 0) {
                                    $result = $iCTI_connexion->query("SELECT COALESCE(max(oid)+1,1) AS oid FROM pmsi.p_rss");
                                    $record = pg_fetch_array($result);
                                    if ($record != FALSE) {
                                        $sequence_rss_id = $record["oid"];
                                    }
                                 } else {
                                    $sequence_rss_id++;
                                }
                                $rss_id = $sequence_rss_id;
                            }
                            
                            
                            // Création RUM

                            $type_autorisation = $BUF_record["type_autorisation_um"];
                            $unite_medicale = $BUF_record["unite_medicale"];
                            $unite_medicale_id = get_unite_medicale($BUF_record["unite_medicale"]);

                            
                            // $sqlcmd = "$sqlcmd_insert_rum VALUES($rss_id, '$finess', $no_rss, $no_rum, '$date_entree', '$date_sortie', '$mode_entree', '$provenance', '$mode_sortie', '$destination', '$date_sortie'::date - '$date_entree'::date, $nb_seances, '$unite_medicale', $diagnostic_principal_id, $diagnostic_relie_id, $unite_medicale_id, '$type_autorisation', $igs2, '$type_autorisation_lit_dedie' ) ";
                            $sqlcmd = "$sqlcmd_insert_rum VALUES($rss_id, '$finess', $no_rss, $no_rum, '$date_entree', '$date_sortie', '$mode_entree', 
                                '$provenance', '$mode_sortie', '$destination','$passage_urgences', $duree_sejour, $nb_seances, '$unite_medicale', 
                                $diagnostic_principal_id, $diagnostic_relie_id, $unite_medicale_id, '$type_autorisation', $igs2, 
                                '$type_autorisation_lit_dedie', $conversion_hp_hc_id) ";
                            $sqlcmd_exec = "$sqlcmd_exec$sqlcmd;";
                            $nbW_rum++;
                            //$toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
                            
                            // création RSS
                            $no_rum_principal = 1;
                            $unite_medicale_principale_id = $unite_medicale_id;
                            
                            // Code postal
                            $code_postal_id = get_code_postal($code_postal);
                            
                            // ghs
                            $ghs_id = @$ghss_rss_array[$no_rss] + 0;
                            if ($ghs_id == 0) {
                                $ghsdia_id = @$ghss_rssdia_array[$no_rss] + 0;
                                if ($ghsdia_id != 0) {
                                    $ghs_id = $ghsdia_id;
                                }
                            }
                            if ($ghs_id == 0) {
                                $ghsbb_id = @$ghss_rssbb_array[$no_rss] + 0;
                                if ($ghsbb_id != 0) {
                                    $ghs_id = @$ghss_rssbb_array[$no_rss] + 0;
                                }
                            }
                            
                            // Prestation principale
                            $prestation_principale_id = @$prestations_principales_array[$no_rss] + 0;
                            
                            // coefficient prudentiel théorique
                            // 0.9930 depuis mars 2017
                            $coefficient_prudentiel_theorique = 0.9930;

                            if ($no_rum == 1) {
                                
                                // identite
                                $nom_rss = "";
                                $nom_rss = @$rssnom_array[get_numrss($no_rss)];
                                $prenom_rss = @$rssprenom_array[get_numrss($no_rss)];
                                $no_patient = get_num(@$rssnopatient_array[get_numrss($no_rss)]);
                                
                                if ($nom_rss == "") {
                                    $nom_rss = @$rssnom_array['-' . get_charAsNum($no_sejour_administratif)];
                                    $prenom_rss = @$rssprenom_array['-' . get_charAsNum($no_sejour_administratif)];
                                }
                                
                                if ($nom_rss == "") {
                                    $nom_rss = "RSS $no_rss";
                                    $prenom_rss = "";
                                }

                                $nom_rss = toSQL($nom_rss);
                                $prenom_rss = toSQL($prenom_rss);
                                
                                $sqlcmd = "$sqlcmd_insert_rss 
                                    VALUES (
                                        $rss_id, $no_patient, '$finess', $no_rss, '$version_groupage', '$code_retour_groupage',
                                        '$date_naissance', '$sexe', '$date_entree', '$date_sortie', '$mode_entree', '$provenance', 
                                        '$mode_sortie', '$destination','$passage_urgences', '$code_postal', $code_postal_id, $poids_bebe, $igs2, '$cma', 
                                        '$groupe_ghm', $duree_sejour, $nb_rsa, 
                                        date_part('year','$date_entree'::date) - date_part('year','$date_naissance'::date) , '$supprime', 
                                        '$date_import',$nb_rum, '$secteur', '$no_sejour_administratif', $nb_seances, '$ghm_fg9', 
                                        $ghm_id, $medecin_rss_id, $comite_medical_id, $ghs_id, 
                                        (date_part('year','$date_sortie'::date) * 100) + date_part('month','$date_sortie'::date), 
                                        $diagnostic_principal_id, $diagnostic_relie_id, $no_rum_principal, 
                                        $unite_medicale_principale_id, $prestation_principale_id, $import_id, 
                                        '$en_cours', '$en_cours_etat', '30', $age_gestationnel, '$date_dernieres_regles'::date, 
                                        '$confirmation_codage', '$type_machine_rdth', '$type_dosimetrie', '$numero_innovation',
                                        $nombre_ivg_anterieures, $annee_ivg_precedente, $nombre_naissances_vivantes_anterieures,
                                        $coefficient_prudentiel_theorique, $conversion_hp_hc_id, $raac_id,$rescrit_tarif_id,
                                        $adm_prod_reshospi_id,$contexte_pat_id,$nb_interventions_id, $np
                                    )
                                ";
                                $sqlcmd_exec = "$sqlcmd_exec$sqlcmd;";
                                $nbW_rss++;
                                //$toResult = execute_sql($sqlcmd, $nbE, $nbW_rss );
                                
                                $sqlcmd = "$sqlcmd_insert_identite VALUES ($rss_id, '$finess', $no_rss, '$nom_rss', '$prenom_rss' ) ";
                                $sqlcmd_exec = "$sqlcmd_exec$sqlcmd;";
                                //$toResult = execute_sql($sqlcmd, $nbE, $nbW_ide );
                                
                            }
                            
                            // RUM supplémentaires
                            else {
                            
                                $nb_rsa = 0;
                                if ($nb_seances == 0 && substr($BUF_record["ghm"], 0 , 2) == "28") {
                                    $nb_seances = 1;
                                }
                                if ($nb_seances > 0 && substr($BUF_record["ghm"], 0 , 2) == "28") {
                                    $nb_rsa = $nb_seances;
                                }
                                
                                // Sur les multi-RUM, la confirmation de codage n'est presente que sur le dernier RUM
                                // Le marqueur de conversion HP-HC est renseigné sur le premier RUM d'hospitalisation complète ou mixte
                                // Il n'apparait donc qu'une fois dans le RSS sur le premier RUM HM ou HC et doit être vide pour les RUMS non concernés
                                $sqlcmd = "UPDATE temp.p_rss SET
                                        date_sortie = '$date_sortie',
                                        mode_sortie = '$mode_sortie',
                                        destination = '$destination',
                                        confirmation_codage = '$confirmation_codage',
                                        nb_rsa = nb_rsa + $nb_rsa,
                                        nb_rum = nb_rum + 1,
                                        nb_seances = nb_seances + $nb_seances,
                                        igs2 = igs2 + $igs2,
                                        mois_sortie = (date_part('year','$date_sortie'::date) * 100) + date_part('month','$date_sortie'::date),
                                        duree_sejour = $duree_sejour + duree_sejour,
                                        coefficient_prudentiel_theorique = $coefficient_prudentiel_theorique,
                                        no_rum_principal = 0, unite_medicale_principale_id = 0,
                                        conversion_hp_hc_id = COALESCE(NULLIF(conversion_hp_hc_id, 0), $conversion_hp_hc_id),
                                        raac_id = COALESCE(NULLIF(raac_id, 0), $raac_id)
                                    WHERE oid = $rss_id ";
                                $sqlcmd_exec .= "$sqlcmd;";
                                //$toResult = execute_sql($sqlcmd, $nbE, $nbW_rss );
                                
                            }
                            
                            
                            // diagnostics

                            $sqlcmd = "$sqlcmd_insert_diagnostic VALUES($rss_id, '$finess', $no_rss, $no_rum, $diagnostic_principal_id, 'DP',  'DP', '0', '$unite_medicale', $unite_medicale_id ) ";
                            
                            $toResult = execute_sql($sqlcmd, $nbE, $nbW_diags );
                            
                            
                            if ($diagnostic_relie_id > 0) {

                                $sqlcmd = "$sqlcmd_insert_diagnostic VALUES($rss_id, '$finess', $no_rss, $no_rum, $diagnostic_relie_id, 'DR', 'DR', '0', '$unite_medicale', $unite_medicale_id  ) ";
                                $sqlcmd_exec = "$sqlcmd_exec$sqlcmd;";
                                $nbW_diags++;
                                //$toResult = execute_sql($sqlcmd, $nbE, $nbW_diags );
                                
                                
                            }
                            
                            
                            $diagnostic_id = 0;
                            
                            foreach ($BUF_record["diags"] as $diagnostic_associe) {
                            
                                $diagnostic_id = get_diagnostic($diagnostic_associe);

                                $sqlcmd = "$sqlcmd_insert_diagnostic VALUES($rss_id, '$finess', $no_rss, $no_rum, $diagnostic_id, 'DA', 'DA', '0', '$unite_medicale', $unite_medicale_id  ) ";
                                $sqlcmd_exec = "$sqlcmd_exec$sqlcmd;";
                                $nbW_diags++;
                                //$toResult = execute_sql($sqlcmd, $nbE, $nbW_diags );
                                

                            }
                            
                            $diagnostic_id = 0;
                            foreach ($BUF_record["diagsdoc"] as $diagnostic_documentaire) {
                                $diagnostic_id = get_diagnostic($diagnostic_documentaire);
                                $sqlcmd = "$sqlcmd_insert_diagnostic VALUES($rss_id, '$finess', $no_rss, $no_rum, $diagnostic_id, 'DD', 'DD', '0', '$unite_medicale', $unite_medicale_id  ) ";
                                $sqlcmd_exec = "$sqlcmd_exec$sqlcmd;";
                                $nbW_diags++;
                                //$toResult = execute_sql($sqlcmd, $nbE, $nbW_diags );
                            }
                            
                            // Génération des actes si pas de RSF
                            if (! $file_exists_RSF || $ENV_TYPEETS != "1")  {
                        
                                foreach ($BUF_record["actes"] as $BUF_acte) {
                            
                                    $BUF_code_acte = trim(substr($BUF_acte , 8, 7));
                                    $BUF_date_acte = trim(substr($BUF_acte , 0, 8));
                                    $BUF_extension_atih = (intval($BUF_record["version_format"]) >= 117) ? trim(substr($BUF_acte , 15, 3)) : "";
                                    $BUF_code_acte .= $BUF_extension_atih;
                                    $acte_id = get_acte($BUF_code_acte);

                                    if ($rss_id > 0) {
                            
                                        $finess = $BUF_record["finess"];

                                        $date_acte = sqlDate($BUF_date_acte);
                                        if (!controle_check_date($BUF_date_acte,$none,$none)) {
                                            $date_acte = sqlDate($BUF_record["date_entree"]);
                                        }
                                        $phase_ccam = trim(substr($BUF_acte , 15 + $BUF_record["offset_format"], 1));
                                        $activite_ccam = trim(substr($BUF_acte , 16 + $BUF_record["offset_format"], 1));
                                        if (! controle_check_num($activite_ccam,1, FALSE,$none,$none)) {
                                            $activite_ccam = "1";
                                        }
                                        $extension_ccam = trim(substr($BUF_acte , 17 + $BUF_record["offset_format"], 1));
                                        $modificateur_ccam_1 = trim(substr($BUF_acte , 18 + $BUF_record["offset_format"], 1));
                                        $modificateur_ccam_2 = trim(substr($BUF_acte , 19 + $BUF_record["offset_format"], 1));
                                        $modificateur_ccam_3 = trim(substr($BUF_acte , 20 + $BUF_record["offset_format"], 1));
                                        $modificateur_ccam_4 = trim(substr($BUF_acte , 21 + $BUF_record["offset_format"], 1));
                                        $remboursement_excp_ccam = trim(substr($BUF_acte , 22 + $BUF_record["offset_format"], 1));
                                        $association_nonprevue_ccam = trim(substr($BUF_acte , 23 + $BUF_record["offset_format"], 1));
                                        $BUF_nombre = trim(substr($BUF_acte , 24 + $BUF_record["offset_format"], 8));
                                        $nombre = get_num($BUF_nombre,1);
                                        
                                        $medecin_id = 0;
                                        // Medecin acte
                                        $code_med = "";
                                        $cle = get_numrss($BUF_record["no_rss"]) . $BUF_code_acte . get_date_AAAAMMJJ($BUF_date_acte) . $activite_ccam ;
                                        if (isset($actmed_array[$cle])){
                                            $code_med = $actmed_array[$cle];
                                            if ($code_med === "") {
                                                $cle = get_numrss($BUF_record["no_rss"]) . $BUF_code_acte . "00000000" . $activite_ccam;
                                                $code_med = $actmed_array[$cle];
                                            }
                                        }

                                        if ($code_med !== "") {
                                            $medecin_id = get_medecin($code_med);
                                        }

                                        
                                        $sqlcmd = "$sqlcmd_insert_acte VALUES( $rss_id,  '$finess',  $no_rss,  $no_rum,  '$unite_medicale', $unite_medicale_id, '$date_acte', $medecin_id, $acte_id, $acte_id, $nombre, '$phase_ccam', '$activite_ccam', '$extension_ccam', '$modificateur_ccam_1', '$modificateur_ccam_2', '$modificateur_ccam_3', '$modificateur_ccam_4', '$remboursement_excp_ccam', '$association_nonprevue_ccam') ";
                                        $sqlcmd_exec = "$sqlcmd_exec$sqlcmd;";
                                        $nbW_actes++;
                                        //$toResult = execute_sql($sqlcmd, $nbE, $nbW_actes );
                                        
                                    }

                                }
                            }
                        
                        }
                        
                        else {
                            logWarnMsg("RSS $no_rss sans RSF non importé");
                        }
                        
                        
                    }
                
                }
            }
        
        }
        
        fclose($handle);
    
    }
    
    if ($sqlcmd_exec != "") {
        $toResult = execute_sql($sqlcmd_exec, $nbE, $nbW_actes );
        $sqlcmd_exec = "";
    }
    $sequence_rss_id++;
    $sqlcmd = "ALTER SEQUENCE pmsi.s_rss RESTART WITH $sequence_rss_id";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    
    commit_trans();
    
    
    
    
    $sqlcmd = "UPDATE temp.p_rss SET nb_seances = 1, nb_rsa = 1 
        WHERE import_id = $import_id AND nb_seances > 1 AND date_sortie = date_entree AND nb_rum > 1";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    
    commit_trans();
    
    $sqlcmd = "UPDATE pmsi.p_imports SET ";
    $sqlcmd = $sqlcmd . "nb_rss = $nbW_rss, ";
    $sqlcmd = $sqlcmd . "nb_rum = $nbW_rum ";
    $sqlcmd = $sqlcmd . "WHERE oid = $import_id";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    
    get_rss("*setarray");

    commit_trans();
    
    
    
    analyse_table_temp("p_rss");
    analyse_table_temp("p_rss_rum");
    analyse_table_temp("p_rss_diagnostics");
    analyse_table_temp("p_rss_actes");
    

    
    logInfoMsg("$nbW_rss RSS créés");
    logInfoMsg("$nbW_rum RUM créés");
    logInfoMsg("$nbW_diags Diagnostics créés");
    if (! $file_exists_RSF || $ENV_TYPEETS != "1")  {
        logInfoMsg("$nbW_actes Actes créés");
    }
    
    $nbW = $nbW_rss + $nbW_rum + $nbW_diags + $nbW_actes;
    
    logInfoMsg("FIN GENERATION DES RUM. $nb lus, $nbW écrits, $nbE erreurs.");

    
}


function generation_rsa() {


    global $file_RSS;
    global $file_RSA;
    global $file_TRA;
    global $file_LEG;
    

    global $file_exists_TRA;
    global $file_exists_LEG;

    logInfoMsg("GENERATION DES RSA");

    $nb = 0;
    $nbI = 0;
    $nbW = 0;
    $nbE = 0;
    $no_ligne = 0;

    $rss_rss_array = array();
    $rss_ghm_array = array();
    $line_rss_array = array();
    $line_ghm_array = array();
    $line_sej_array = array();
    
    $rsa_linerss_array = array();
    $rsa_leg_array = array();
    
    $finess = '';
    begin_trans();
    


    // GHM par RSS (pour controle concordance)
    $nb_rss = 0;
    $der_rss = 0;
    
    $handle = @fopen($file_RSS, "r");
    if ($handle) {
        while (!feof($handle)) {
            $buffer = fgets($handle, 99999);
            
            $no_ligne++;
            if (trim($buffer) != "" && $no_ligne < 1000000000000000) {

                
                $BUF_record = read_rum_line($buffer);
                
                if ($BUF_record["type_enregistrement"] == "RUM") {

                    
                    $no_rss =  get_numrss($BUF_record["no_rss"]);
                    
                    if ($no_rss != $der_rss) { // A suppr ?
                        $nb_rss++;
                        $der_rss = $no_rss;
                        $rss_rss_array[$nb_rss] = $no_rss;
                        $rss_ghm_array[$nb_rss] = trim($BUF_record["ghm"]);
                    }
                    
                    $line_rss_array[$no_ligne] = $no_rss; // A suppr ?
                    $line_ghm_array[$no_ligne] = $BUF_record["ghm"];
                    $line_sej_array[$no_ligne] = get_charAsNum($BUF_record["no_sejour_administratif"]);

                }
            }
        }
    }
    
    if ($file_exists_TRA) {
            
        $no_ligne = 0;
        
        $handle = @fopen($file_TRA, "r");
        if ($handle) {
            while (!feof($handle)) {
                $buffer = fgets($handle, 99999);
                
                $no_ligne++;
                if (trim($buffer) != "" && $no_ligne < 1000000000000000) {

                    $BUF_record = read_tra_line($buffer);

                    
                    if ($BUF_record["type_enregistrement"] == "TRA") {

                        $no_rsa = get_num($BUF_record["no_rsa"]);
                        
                        $ligne_rss =  get_num($BUF_record["ligne_rss"]);
                        $doControlTRA_GHM = $BUF_record["doControlTRA_GHM"];
						
                        $traVersion = $ligne_rss === 0 ? "druide_2023" : "old";
                        if ($traVersion === "druide_2023"){
                            $rss_rss_array[$no_rsa] = get_charAsNum($BUF_record["no_rss"]);
							$rss_ghm_array[$no_rsa] = $BUF_record["ghm"];
                        } else {
                            // Ancienne version
                            $no_sejour_administratif =  get_charAsNum($BUF_record["no_sejour_administratif"]);
							$ghm =  $BUF_record["ghm"];
						
							if ($line_sej_array[$ligne_rss] == $no_sejour_administratif) {
								$rss_rss_array[$no_rsa] = $line_rss_array[$ligne_rss];
								$rss_ghm_array[$no_rsa] = trim($line_ghm_array[$ligne_rss]);
							}
                        }							
                    }
                }
            }
        }
    }
    
    // Recherche des codes erreurs de retour de groupage
    if ($file_exists_LEG) {
        
        $error_leg_file = false;
        
        logInfoMsg("TRAITEMENT FICHIER LEG");
        
        $no_ligne_leg = 0;
        $leg_query = "INSERT INTO temp.p_rss_leg (finess, no_rsa, rss_id, code_retour_id, nombre) ";
        
        $handle = @fopen($file_LEG, "r");
        if ($handle) {
            
            while (!feof($handle)) {
                $buffer = fgets($handle, 99999);
                
                $no_ligne_leg++;
                if (trim($buffer) != "" && $no_ligne_leg < 1000000000000000) {
                    
                    $BUF_record = read_leg_line($buffer);
                    
                    if ($BUF_record["type_enregistrement"] == "LEG") {
                        // Pour chaque numéro de RSA, stocke tous les codes erreurs de groupage
                        $rsa_leg_array[get_num($BUF_record["no_rsa"])] = $BUF_record["codes"];
                        // Récupère le finess aussi au cas où
                        $finess = $BUF_record["finess"];
                    }
                    // Si le fichier présente une erreur de format, on passe le flag error_leg_file à true
                    else {
                        $error_leg_file = true;
                    }
                }
            }
            fclose($handle);
        }
    }
    
    
    $no_ligne = 0;
    
    $nb_rsa = 0;
    
    $finess_error = FALSE;
    $format_error = FALSE;
    $finess_first = "";
    
    $pb_concordance = FALSE;
    
    $handle = @fopen($file_RSA, "r");
    if ($handle) {
        while (!feof($handle)) {
            $buffer = fgets($handle, 99999);
            
            $no_ligne++;
            if (trim($buffer) != "" && $no_ligne < 1000000000000000) {
            
                $nb++;
                
                $BUF_record = read_rsa_line($buffer);
                
                if ($BUF_record["type_enregistrement"] == "RSA") {
                
                    $nb_rsa++;
                    $no_rsa =  get_num($BUF_record["no_rsa"]);

                    if ($pb_concordance == FALSE) {
                        if ($doControlTRA_GHM && @$rss_ghm_array[$no_rsa] != trim($BUF_record["ghm_genrsa"])) {
                            $pb_concordance = TRUE;
                        }
                    }

                }
            }
        
        }
        
        fclose($handle);
    
    }
    
    
    $sqlcmd_exec = "";
    
    if ($pb_concordance == FALSE) {
    
    
    
        $no_ligne = 0;
        $nb = 0;
        $nb_rsa_err = 0;
        $nb_leg = 0;

        
        $pb_concordance = FALSE;
        
        $handle = @fopen($file_RSA, "r");
        if ($handle) {
            while (!feof($handle)) {
                $buffer = fgets($handle, 99999);
                
                if (trim($buffer) != "" && $no_ligne < 1000000000000000) {
                
                    $nb++;
                    
                    $BUF_record = read_rsa_line($buffer);
                    
                    if ($BUF_record["type_enregistrement"] == "RSA") {
                    
                        if (strlen($sqlcmd_exec) > 64000) {
                            $toResult = execute_sql($sqlcmd_exec, $nbE, $nbW_actesxx );
                            $sqlcmd_exec = "";
                        }
                    
                        $no_ligne++;
                        
                        $no_rsa = get_num($BUF_record["no_rsa"]);
                        $no_rss = $rss_rss_array[$no_rsa] + 0;
                        $rss_id = get_rss($no_rss) + 0;
                        $ghm_code = $BUF_record["ghm"];
                        $ghm_id = get_ghm($ghm_code);
                        $code_retour = $BUF_record["code_retour"];
                        $ghm_genrsa_code = $BUF_record["ghm_genrsa"];
                        $ghm_genrsa_id = get_ghm($ghm_genrsa_code);
                        $code_retour_genrsa = $BUF_record["code_retour_genrsa"];
                        $ghs_genrsa_code_in = $BUF_record["ghs_genrsa"];
                        $ghs_genrsa_id = get_ghs($ghs_genrsa_code_in);
                        $nb_exh = get_num($BUF_record["nb_exh"]);
                        $nb_exb = get_num($BUF_record["nb_exb"]);
                        $forfait_dialyse = $BUF_record["forfait_dialyse"];
                        $nb_sup_dialyse_1 = get_num($BUF_record["nb_sup_dialyse_1"]);
                        $nb_sup_dialyse_2 = get_num($BUF_record["nb_sup_dialyse_2"]);
                        $nb_sup_dialyse_3 = get_num($BUF_record["nb_sup_dialyse_3"]);
                        $nb_sup_dialyse_4 = get_num($BUF_record["nb_sup_dialyse_4"]);
                        $nb_actes_9510 = get_num($BUF_record["nb_actes_9510"]);
                        $nb_actes_9511 = get_num($BUF_record["nb_actes_9511"]);
                        $nb_actes_9512 = get_num($BUF_record["nb_actes_9512"]);
                        $nb_actes_9515 = get_num($BUF_record["nb_actes_9515"]);
                        $nb_actes_9524 = get_num($BUF_record["nb_actes_9524"]);
                        $nb_actes_9621 = get_num($BUF_record["nb_actes_9621"]);
                        $nb_actes_9622 = get_num($BUF_record["nb_actes_9622"]);
                        $nb_actes_6523 = get_num($BUF_record["nb_actes_6523"]);
                        $nb_sup_hyperbare = get_num($BUF_record["nb_sup_hyperbare"]);
                        $nb_sup_apherese = get_num($BUF_record["nb_sup_apherese"]);
                        $type_prestation_prelevement_organe = $BUF_record["type_prestation_prelevement_organe"];
                        $nb_sup_sra = get_num($BUF_record["nb_sup_sra"]);
                        $nb_sup_rea = get_num($BUF_record["nb_sup_rea"]);
                        $nb_sup_si = get_num($BUF_record["nb_sup_si"]);
                        $nb_sup_stf = get_num($BUF_record["nb_sup_stf"]);
                        $nb_sup_ssc = get_num($BUF_record["nb_sup_ssc"]);
                        $nb_sup_src = get_num($BUF_record["nb_sup_src"]);
                        $nb_sup_nn1 = get_num($BUF_record["nb_sup_nn1"]);
                        $nb_sup_nn2 = get_num($BUF_record["nb_sup_nn2"]);
                        $nb_sup_nn3 = get_num($BUF_record["nb_sup_nn3"]);
                        $nb_sup_rep = get_num($BUF_record["nb_sup_rep"]);
                        $no_rum_dp = get_num($BUF_record["no_rum_dp"]);
                        $top_uhcd = $BUF_record["top_uhcd"];
                        $top_ghs_minore = str_pad(trim($BUF_record["top_ghs_minore"]), 1, "0"); // Force à 0 si non renseigné
                        $nb_rdth = get_num($BUF_record["nb_rdth"]);
                        $passage_lit_sp = $BUF_record["passage_lit_sp"];
                        $nb_faisceaux = get_num($BUF_record["nb_faisceaux"]);
                        $nb_sup_ant = get_num($BUF_record["nb_sup_ant"]);
                        $nb_sup_rap = get_num($BUF_record["nb_sup_rap"]);
                        $nb_sup_sdc = get_num($BUF_record["nb_sup_sdc"]);
                        $age_jours = get_num($BUF_record["age_jours"], -1);
                        $top_radiation_partielle_avastin = str_pad(trim($BUF_record["top_radiation_part_avastin"]), 1, "0"); // Force à 0 si non renseigné
                        
                        $finess = $BUF_record["finess"];
                        $version_format = $BUF_record["version_format"];
                        $version_format_rsa = $BUF_record["version_format_rsa"];
                        $version_groupage = $BUF_record["version_groupage"];
                        $version_groupage_genrsa = $BUF_record["version_groupage_genrsa"];
                        $age_annees = get_num($BUF_record["age_annees"], -1);
                        $sexe = $BUF_record["sexe"];
                        $mode_entree = $BUF_record["mode_entree"];
                        $provenance = $BUF_record["provenance"];
                        $mode_sortie = $BUF_record["mode_sortie"];
                        $destination = $BUF_record["destination"];
                        $annee_sortie = get_num($BUF_record["annee_sortie"]);
                        $mois_sortie = get_num($BUF_record["mois_sortie"]);
                        $duree_sejour = get_num($BUF_record["duree_sejour"]);
                        $code_geographique_pmsi_id = get_code_geographique_pmsi($BUF_record["code_geographique"]);
                        $poids_entree = get_num($BUF_record["poids_entree"]);
                        $age_gestationnel = get_num($BUF_record["age_gestationnel"]);
                        $delai_dernieres_regles = get_num($BUF_record["delai_dernieres_regles"]);
                        $nb_seances = get_num($BUF_record["nombre_seances"]);
                        $type_exb = $BUF_record["type_exb"];
                        $top_radiation_partielle_alimta = str_pad(trim($BUF_record["top_radiation_partielle_alimta"]), 1, "0"); // Force à 0 si non renseigné
                        $confirmation_codage = $BUF_record["confirmation_codage"];
                        $nb_aut_pgv = get_num($BUF_record["nb_aut_pgv"]);
                        $top_valve_aortique = str_pad(trim($BUF_record["top_valve_aortique"]), 1, "0"); // Force à 0 si non renseigné
                        $type_generation_automatique = get_num($BUF_record["type_generation_automatique"]);
                        $ghs_hors_innovation_id = get_ghs($BUF_record["ghs_hors_innovation"]);
                        $type_machine_rdth = $BUF_record["type_machine_rdth"];
                        $type_dosimetrie = $BUF_record["type_dosimetrie"];
                        $numero_innovation = $BUF_record["numero_innovation"];
                        $diagnostic_principal_id = get_diagnostic($BUF_record["diagnostic_principal"]);
                        $diagnostic_relie_id = get_diagnostic($BUF_record["diagnostic_relie"]);
                        $nb_das = get_num($BUF_record["nb_das"]);
                        
                        $sqlcmd = "INSERT INTO temp.p_rsa(
                                    no_rsa, no_rss, rss_id, ghm_id, code_retour, ghm_genrsa_id, code_retour_genrsa, 
                                    ghs_genrsa_id, nb_exh, nb_exb, forfait_dialyse, 
                                    nb_sup_dialyse_1, nb_sup_dialyse_2, nb_sup_dialyse_3, nb_sup_dialyse_4, 
                                    nb_actes_9510, nb_actes_9511, nb_actes_9512, nb_actes_9515, nb_actes_9524, nb_actes_9621,
                                    nb_actes_9622, nb_actes_6523, nb_sup_hyperbare, nb_sup_apherese, type_prestation_prelevement_organe, 
                                    nb_sup_sra, nb_sup_rea, nb_sup_si, nb_sup_stf, nb_sup_ssc, nb_sup_src, nb_sup_nn1, nb_sup_nn2, nb_sup_nn3, nb_sup_rep, 
                                    no_rum_dp, top_uhcd, nb_rdth, passage_lit_sp, nb_faisceaux, nb_sup_ant, nb_sup_rap, top_ghs_minore, age_jours, top_radiation_partielle_avastin, nb_sup_sdc,
                                    finess, version_format, version_format_rsa, version_groupage, version_groupage_genrsa,
                                    age_annees, sexe, mode_entree, provenance, mode_sortie, destination,
                                    annee_sortie, mois_sortie, duree_sejour, code_geographique_pmsi_id, poids_entree, age_gestationnel, delai_dernieres_regles,
                                    nb_seances, type_exb, top_radiation_partielle_alimta, confirmation_codage, nb_aut_pgv,
                                    top_valve_aortique, type_generation_automatique, ghs_hors_innovation_id, type_machine_rdth,
                                    type_dosimetrie, numero_innovation, diagnostic_principal_id, diagnostic_relie_id, nb_das)
                            VALUES ($no_rsa, $no_rss, $rss_id, $ghm_id, '$code_retour', $ghm_genrsa_id, '$code_retour_genrsa', 
                                    $ghs_genrsa_id, $nb_exh, $nb_exb, '$forfait_dialyse', 
                                    $nb_sup_dialyse_1, $nb_sup_dialyse_2, $nb_sup_dialyse_3, $nb_sup_dialyse_4, 
                                    $nb_actes_9510, $nb_actes_9511,$nb_actes_9512, $nb_actes_9515, $nb_actes_9524, $nb_actes_9621, 
                                    $nb_actes_9622, $nb_actes_6523, $nb_sup_hyperbare, $nb_sup_apherese, '$type_prestation_prelevement_organe', 
                                    $nb_sup_sra, $nb_sup_rea, $nb_sup_si, $nb_sup_stf, $nb_sup_ssc, $nb_sup_src, $nb_sup_nn1, $nb_sup_nn2, $nb_sup_nn3, $nb_sup_rep, 
                                    $no_rum_dp, '$top_uhcd', $nb_rdth, '$passage_lit_sp', $nb_faisceaux, $nb_sup_ant, $nb_sup_rap, '$top_ghs_minore', $age_jours, '$top_radiation_partielle_avastin', $nb_sup_sdc,
                                    '$finess', '$version_format', '$version_format_rsa', '$version_groupage', '$version_groupage_genrsa',
                                    $age_annees, '$sexe', '$mode_entree', '$provenance', '$mode_sortie', '$destination',
                                    $annee_sortie, $mois_sortie, $duree_sejour, $code_geographique_pmsi_id, $poids_entree, $age_gestationnel, $delai_dernieres_regles,
                                    $nb_seances, '$type_exb', '$top_radiation_partielle_alimta', '$confirmation_codage', $nb_aut_pgv,
                                    '$top_valve_aortique', '$type_generation_automatique', $ghs_hors_innovation_id, '$type_machine_rdth',
                                    '$type_dosimetrie', '$numero_innovation', $diagnostic_principal_id, $diagnostic_relie_id, $nb_das)";
                    
                        $sqlcmd_exec = "$sqlcmd_exec$sqlcmd;";
                        $nbW++;
                        //$toResult = execute_sql($sqlcmd, $nbE, $nbW );
                        
                        // Insertion des suppléments de radiothérapie
                        if ($nb_rdth > 0) {
                            for ($i = 1; $i <= $nb_rdth ; $i++) {
                                $ghs_id = get_ghs($BUF_record["supprdth"][$i]["ghs"]);
                                $nb_supplements = $BUF_record["supprdth"][$i]["nb_supplements"];
                                if (trim($nb_supplements) === "") {
                                    $nb_supplements = 0;
                                } 
                                $sqlcmd = "
                                    INSERT INTO temp.p_rsa_rdth(
                                        ghs_id, nb_supplements, rss_id)
                                    VALUES (
                                        $ghs_id, 
                                        ".$nb_supplements.", 
                                        $rss_id)
                                ";
                                $sqlcmd_exec = "$sqlcmd_exec$sqlcmd;";
                                $nbW++;
                                //$toResult = execute_sql($sqlcmd, $nbE, $nbW);
                            }
                        }
                        /*** Erreurs de groupage ***/
                        // Checke si le fichier leg est valide, si le RSA a des erreurs de groupage et qu'il ne s'agit pas d'un dossier hors ghm
                            if ($file_exists_LEG && isset($rsa_leg_array[$no_rsa])) {
                                if (!$error_leg_file && $rsa_leg_array[$no_rsa] != '' && $rss_id != 0) {
                                    $nb_rsa_err++;
                                    // Met tous les codes d'erreur de groupage dans un tableau trié
                                    $codes_retour = explode(';', $rsa_leg_array[$no_rsa]);
                                    sort($codes_retour);
                                    $previous = '';
                                    $nombre = 0;
                                    // Construit un tableau associant un code d'erreur et son nombre d'occurences. Uun RSA peut avoir plusieurs fois la même erreur,
                                    // exemple. Le RSA XXXX présente les erreurs C170, C093, C093, C093, G180. $codes_retour vaudra ['C093','C093','C093','C170','G180']
                                    // $uniq_codes sera de la forme
                                    // [
                                    //  'C093' => 3;
                                    //  'C170' => 1;
                                    //  'G180' => 1;
                                    //  ]
                                    $uniq_codes = array();
                                    foreach ($codes_retour as $code_retour) {
                                        if ($code_retour != $previous) {
                                            $nombre = 1;
                                            $previous = $code_retour;
                                        } else {
                                            $nombre++;
                                        }
                                        $uniq_codes[$code_retour] = $nombre;
                                    }
                                    foreach ($uniq_codes as $key => $code_retour) {
                                        $nb_leg++;
                                        // Recherche l'oid du code d'erreur groupage
                                        $code_retour_id = get_code_retour($key);
                                        if (trim($code_retour_id) === "") {
                                            $code_retour_id = 0;
                                        }
                                        // Construction de la requête avec les infos qui vont bien
                                        $sqlcmd = $leg_query . "VALUES ('$finess', $no_ligne, $rss_id, $code_retour_id, $uniq_codes[$key])";
                                        $sqlcmd_exec = "$sqlcmd_exec$sqlcmd;";
                                        $nbW++;
                                        //$toResult = execute_sql($sqlcmd, $nbE, $nbW );
                                    }
                                }
                            }
                    }
                }
            }

            fclose($handle);
        
        }
    

    
    }

    if ($sqlcmd_exec != "") {
        $toResult = execute_sql($sqlcmd_exec, $nbE, $nbW_actesxx );
        $sqlcmd_exec = "";
    }

    commit_trans();
    
    analyse_table_temp("p_rsa");

    if (!$error_leg_file) {
        logInfoMsg("GENERATION DES ERREURS DE GROUPAGE. $nb_rsa_err RSA impactés, $nb_leg erreurs de groupage remontées");
    }
    else {
        logWarnMsg("Le fichier LEG d'erreurs de groupage n'est pas au bon format de données. Aucune erreur de groupage remontée");
    }
    logInfoMsg("FIN GENERATION DES RSA. $nb lus, $nbW écrits, $nbE erreurs.");

    
}




// Traitement des RSF
function generation_rsf_sans_rss() {

    
    global $iCTI_connexion;
    global $ENV_TYPEETS;
    global $annee_fin;
    
    global $import_id;
    global $ENV_PMSIPROVIDER;
    global $ENV_PMSIPROVIDER2;

    global $file_RSF;
    global $file_exists_RSF;

    global $rssmed_array;
    global $rssnom_array;
    global $rssprenom_array;
    
    global $current_rsfa_index;

    logInfoMsg("INITIALISATION DES RSF SANS RSS");
    
    $w_ENV_PMSIPROVIDER = $ENV_PMSIPROVIDER;
    
    begin_trans();
    
    $nb = 0;
    $nbW = 0;
    $nbW_rss = 0;
    $nbW_rum = 0;
    $nbW_detail = 0;
    $nbW_lpp = 0;
    $nbW_ucd = 0;
    $nbE = 0;

    commit_trans();
    
    $sqlcmd_insert_rum = "INSERT INTO temp.p_rss_rum( ";
    $sqlcmd_insert_rum = $sqlcmd_insert_rum . "rss_id,  ";
    $sqlcmd_insert_rum = $sqlcmd_insert_rum . "finess,  ";
    $sqlcmd_insert_rum = $sqlcmd_insert_rum . "no_rss,  ";
    $sqlcmd_insert_rum = $sqlcmd_insert_rum . "no_rum,  ";
    $sqlcmd_insert_rum = $sqlcmd_insert_rum . "date_entree,  ";
    $sqlcmd_insert_rum = $sqlcmd_insert_rum . "date_sortie,  ";
    $sqlcmd_insert_rum = $sqlcmd_insert_rum . "mode_entree,  ";
    $sqlcmd_insert_rum = $sqlcmd_insert_rum . "provenance,  ";
    $sqlcmd_insert_rum = $sqlcmd_insert_rum . "mode_sortie,  ";
    $sqlcmd_insert_rum = $sqlcmd_insert_rum . "destination,  ";
    $sqlcmd_insert_rum = $sqlcmd_insert_rum . "duree_sejour,  ";
    $sqlcmd_insert_rum = $sqlcmd_insert_rum . "nb_seances,  ";
    $sqlcmd_insert_rum = $sqlcmd_insert_rum . "unite_medicale,  ";
    $sqlcmd_insert_rum = $sqlcmd_insert_rum . "diagnostic_principal_id,  ";
    $sqlcmd_insert_rum = $sqlcmd_insert_rum . "diagnostic_relie_id,  ";
    $sqlcmd_insert_rum = $sqlcmd_insert_rum . "unite_medicale_id,  ";
    $sqlcmd_insert_rum = $sqlcmd_insert_rum . "type_autorisation, ";
    $sqlcmd_insert_rum = $sqlcmd_insert_rum . "igs2 ";
    $sqlcmd_insert_rum = $sqlcmd_insert_rum . ") ";
    
    $sqlcmd_insert_rss = "INSERT INTO temp.p_rss(";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "oid,  ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "no_patient, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "finess, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "no_rss, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "version_groupage, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "date_naissance, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "sexe, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "date_entree, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "date_sortie, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "mode_entree, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "provenance, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "mode_sortie, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "destination, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "code_postal, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "code_postal_id, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "poids_bebe, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "igs2, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "cma, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "groupe_ghm, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "duree_sejour, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "nb_rsa, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "age, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "supprime, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "date_import, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "nb_rum, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "secteur, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "no_sejour_administratif, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "nb_seances, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "ghm_fg9, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "ghm_id, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "medecin_rss_id, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "ghs_id, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "mois_sortie, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "diagnostic_principal_id, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "diagnostic_relie_id, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "no_rum_principal, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "unite_medicale_principale_id, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "import_id, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "en_cours, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "en_cours_etat, ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . "traitement_epmsi, ";
    $sqlcmd_insert_rss .= "
        age_gestationnel,
        date_dernieres_regles,
        confirmation_codage,
        type_machine_rdth,
        type_dosimetrie,
        numero_innovation,
        nombre_ivg_anterieures,
        annee_ivg_precedente,
        nombre_naissances_vivantes_anterieures,
        coefficient_prudentiel_theorique
    ";
    $sqlcmd_insert_rss = $sqlcmd_insert_rss . ") ";

    $sqlcmd_insert_identite = "INSERT INTO temp.p_identites( ";
    $sqlcmd_insert_identite = $sqlcmd_insert_identite . "rss_id, ";
    $sqlcmd_insert_identite = $sqlcmd_insert_identite . "finess,  ";
    $sqlcmd_insert_identite = $sqlcmd_insert_identite . "no_rss, ";
    $sqlcmd_insert_identite = $sqlcmd_insert_identite . "nom, ";
    $sqlcmd_insert_identite = $sqlcmd_insert_identite . "prenom ";
    $sqlcmd_insert_identite = $sqlcmd_insert_identite . ") ";
    
    
    $no_ligne = 0;
    $BUF_version = "";
    $last_no_rss = -9999999999999;
    
    
    // prestation RSS
    
    if ($file_exists_RSF && $ENV_TYPEETS != "1") {
        $current_rsfa_index = 0;
        $handle = @fopen($file_RSF, "r");
        if ($handle) {
            while (!feof($handle)) {
                $buffer = fgets($handle, 99999);
                
                if (trim($buffer) != "" ) {

                    $BUF_record = read_rsf_partial_line($buffer);
                    
                    if ($BUF_record["ok"] == TRUE) {

                        // ENTETE RSF
                        if ($BUF_record["type_enregistrement"] == "A") {
                        
                            
                            
                            // RSS
                            if (controle_check_num($BUF_record["no_rss"],0,FALSE,$erreur,$commentaire)) {
                                $no_rss = get_numrss($BUF_record["no_rss"]);
                            }

                        }
                        
                    }
                    
                }
                
            }
            
        }
    }
    
    $current_rsfa_index = 0;
    
    $sequence_rss_id = 0;
    $sqlcmd_exec = "";
    
    
    $handle = @fopen($file_RSF, "r");
    if ($handle) {
        while (!feof($handle)) {
            $buffer = fgets($handle, 99999);
            
            $no_ligne++;
            if (trim($buffer) != "" ) {
            
                $nb++;
                
                $BUF_record = read_rsf_line($buffer, TRUE, FALSE, FALSE, FALSE);
                
                
                // ENTETE RSF
                if ($BUF_record["type_enregistrement"] == "A") {

                    if (get_numrss($BUF_record["no_rss"]) == 0) {
                        // $BUF_record["no_rss"] = $BUF_record["no_facture"] + 99000000000;
                        $BUF_record["no_rss"] = '9' . str_pad(ltrim($BUF_record["no_facture"], '0'), 8, '0', STR_PAD_LEFT);
                    }
                    $no_rss = get_numrss($BUF_record["no_rss"]);
                    $rss_ok = TRUE;

                    if ($rss_ok == TRUE) {
                    
                        $rsf_ok = TRUE;
                        
                        if ($rsf_ok == TRUE) {
                            
                            $rss_id = get_rss($no_rss);
                            
                            if (get_num($rss_id) == 0 && $no_rss != $last_no_rss) {
                                if (strlen($sqlcmd_exec) > 64000) {
                                    $toResult = execute_sql($sqlcmd_exec, $nbE, $nbW_actesxx );
                                    $sqlcmd_exec = "";
                                }
                        
                                $no_patient = 0;
                                $finess = $BUF_record["finess"];
                                $no_rss = get_numrss($BUF_record["no_rss"]);
                                $en_cours = "0";
                                $en_cours_etat = "";

                                $version_groupage = "";
                                if (controle_check_date($BUF_record["date_naissance"],$none,$none, true)) {
                                    $date_naissance = sqlDate($BUF_record["date_naissance"]);
                                }
                                else {
                                    $date_naissance = default_birth_date($BUF_record["date_naissance"]);
                                }
                                $sexe = $BUF_record["sexe"];
                                if ($sexe != "1" && $sexe != "2" && $sexe != "3" ) {
                                    $sexe = "1";
                                    if ($w_ENV_PMSIPROVIDER == "shs") {
                                        if ($sexe == "3" || $sexe == "5") {
                                            $sexe = "2";
                                        }
                                        else {
                                            $sexe = "1";
                                        }
                                    }
                                }
                                if (controle_check_date($BUF_record["date_entree"],$none,$none, true)) {
                                    $date_entree = sqlDate($BUF_record["date_entree"]);
                                }
                                else {
                                    $date_entree = "$annee_fin-01-01";
                                }
                                $mode_entree = "8";
                                $provenance = "";
                                if (controle_check_date($BUF_record["date_sortie"],$none,$none, true)) {
                                    $date_sortie = sqlDate($BUF_record["date_sortie"]);
                                }
                                else {
                                    $date_sortie = $date_entree;
                                }
                                $mode_sortie = "8";
                                $destination = "";
                                $code_postal = trim($BUF_record["code_postal"]);
                                $code_postal_id = 0;
                                $poids_bebe = 0;
                                $igs2 = 0;
                                $cma = "";
                                $groupe_ghm = "";
                                $duree_sejour = 0;
                                $nb_rsa = 1;
                                $age = 0;
                                $supprime = "";
                                $date_import = "2099-12-31";
                                $nb_rum = 1;
                                $secteur = "";
                                $no_sejour_administratif = get_charAsNum($BUF_record["no_sejour_administratif"]);
                                $nb_seances = 0;
                                $ghm_fg9 = "";
                                $ghm_id = 0;
                                $medecin_rss_id = 0;
                                $ghs_id = 0;
                                $mois_sortie = 0;
                                $diagnostic_principal_id = 0;
                                $diagnostic_relie_id = 0;
                                $no_rum_principal = 1;
                                $unite_medicale_principale_id = 0;
                                $age_gestationnel = 0;
                                $date_dernieres_regles = "2099-12-31";
                                $confirmation_codage = "0";
                                $type_machine_rdth = "0";
                                $type_dosimetrie = "0";
                                $numero_innovation = "";
                                $nombre_ivg_anterieures = 0;
                                $annee_ivg_precedente = 0;
                                $nombre_naissances_vivantes_anterieures = 0;

                                
                                
                                // OID rss
                                $oid = 0;
                                $no_rum = 1;
                                if ($no_rum == 1) {
                                    if ($sequence_rss_id == 0) {
                                        $result = $iCTI_connexion->query("SELECT MAX(oid) AS oid
                                                                        FROM
                                                                        (
                                                                        SELECT COALESCE(max(oid)+1,1) AS oid FROM pmsi.p_rss
                                                                        UNION
                                                                        SELECT COALESCE(max(oid)+1,1) AS oid FROM temp.p_rss
                                                                        ) subview");
                                        $ok = TRUE;
                                        while ($ok == TRUE) {
                                            $ok = FALSE;
                                            $record = pg_fetch_array($result);
                                            if ($record != FALSE) {
                                                $ok = TRUE;
                                                $sequence_rss_id = $record["oid"];
                                            }
                                        }
                                    }
                                    else {
                                        $sequence_rss_id++;
                                    }
                                    $rss_id = $sequence_rss_id;
                                }
                                
                                // Medecin RSS
                                $code_med = "";
                                $code_med = @$rssmed_array[get_numrss($BUF_record["no_rss"])];
                                if ($code_med != "") {
                                    $medecin_rss_id = get_medecin($code_med);
                                }
                                
                                
                                
                                
                                // Création RUM

                                $type_autorisation = "";
                                $unite_medicale = "";
                                $unite_medicale_id = 0;

                                $sqlcmd = "$sqlcmd_insert_rum VALUES($rss_id, '$finess', $no_rss, $no_rum, '$date_entree', '$date_sortie', '$mode_entree',  '$provenance', '$mode_sortie', '$destination', '$date_sortie'::date - '$date_entree'::date, $nb_seances, '$unite_medicale', $diagnostic_principal_id, $diagnostic_relie_id, $unite_medicale_id, '$type_autorisation', 0 ) ";
                                $sqlcmd_exec = "$sqlcmd_exec$sqlcmd;";
                                $nbW_rum++;
                                //$toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
                                
                                // création RSS
                                $no_rum_principal = 1;
                                $unite_medicale_principale_id = 0;
                                
                                // coefficient prudentiel théorique
                                // 0.9930 depuis mars 2017
                                $coefficient_prudentiel_theorique = 0.9930;
                                
                                
                                $sqlcmd = "$sqlcmd_insert_rss 
                                    VALUES (
                                        $rss_id, $no_patient, '$finess', $no_rss, '$version_groupage', 
                                        '$date_naissance', '$sexe', '$date_entree', '$date_sortie', '$mode_entree', '$provenance', 
                                        '$mode_sortie', '$destination', '$code_postal', $code_postal_id, $poids_bebe, $igs2, '$cma', 
                                        '$groupe_ghm', '$date_sortie'::date - '$date_entree'::date, $nb_rsa, 
                                        date_part('year','$date_entree'::date) - date_part('year','$date_naissance'::date) , '$supprime', 
                                        '$date_import', $nb_rum, '$secteur', '$no_sejour_administratif', $nb_seances, '$ghm_fg9', 
                                        $ghm_id, $medecin_rss_id, $ghs_id, 
                                        (date_part('year','$date_sortie'::date) * 100) + date_part('month','$date_sortie'::date), 
                                        $diagnostic_principal_id, $diagnostic_relie_id, $no_rum_principal, 
                                        $unite_medicale_principale_id, $import_id, 
                                        '$en_cours', '$en_cours_etat', '30', $age_gestationnel, '$date_dernieres_regles'::date, 
                                        '$confirmation_codage', '$type_machine_rdth', '$type_dosimetrie', '$numero_innovation',
                                        $nombre_ivg_anterieures, $annee_ivg_precedente, $nombre_naissances_vivantes_anterieures,
                                        $coefficient_prudentiel_theorique
                                    )
                                ";
                                $sqlcmd_exec = "$sqlcmd_exec$sqlcmd;";
                                $nbW_rss++;
                                //$toResult = execute_sql($sqlcmd, $nbE, $nbW_rss );
                                
                                new_rss($no_rss, $rss_id);
                                
                            
                                
                                // identite
                                $nom_rss = "";
                                $nom_rss = trim(@$rssnom_array[get_num($no_rss)]);
                                $prenom_rss = trim(@$rssprenom_array[get_num($no_rss)]);
                                
                                if ($nom_rss == "") {
                                    $nom_rss = trim(@$rssnom_array['-' . get_charAsNum($no_sejour_administratif)]);
                                    $prenom_rss = trim(@$rssprenom_array['-' . get_charAsNum($no_sejour_administratif)]);
                                }
                                
                                if ($nom_rss == "") {
                                    $nom_rss = "RSS $no_rss";
                                    $prenom_rss = "";
                                }

                                $nom_rss = toSQL($nom_rss);
                                $prenom_rss = toSQL($prenom_rss);

                                $sqlcmd = "$sqlcmd_insert_identite VALUES ($rss_id, '$finess', $no_rss, '$nom_rss', '$prenom_rss' ) ";
                                $sqlcmd_exec = "$sqlcmd_exec$sqlcmd;";
                                //$toResult = execute_sql($sqlcmd, $nbE, $nbW_ide );
                            }
                        
                        }
                    
                    }
                    
                    $last_no_rss = $no_rss;
                
                }

            }
        }
        
        fclose($handle);
    
    }
    
    if ($sqlcmd_exec != "") {
        $toResult = execute_sql($sqlcmd_exec, $nbE, $nbW_actesxx );
        $sqlcmd_exec = "";
    }
    
    
    get_rss("*setarray");
    
    $sequence_rss_id++;
    $sqlcmd = "ALTER SEQUENCE pmsi.s_rss RESTART WITH $sequence_rss_id";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    
    commit_trans();
    
    analyse_table_temp("p_rss");
    analyse_table_temp("p_rss_rum");
    
    
    logInfoMsg("$nbW_rss RSS fictifs créés");
    logInfoMsg("$nbW_rum RUM fictifs créés");
    
    $nbW = $nbW_rss + $nbW_rum ;

    
    logInfoMsg("FIN INITIALISATION DES RSF SANS RSS. $nb lus, $nbW écrits, $nbE erreurs.");

    
}



// Traitement des RSF
function generation_rsf() {

    global $iCTI_connexion;
    global $ENV_TYPEETS;
    global $ENV_OPTPMSI_GHSBB;
    global $ENV_OPTPMSI_FSD_B;
    
    global $import_id;

    global $annee_mois_fin;

    global $file_ACTMED;
    global $file_RSS;
    global $file_RSF;

	global $file_exists_VSE;
    global $file_exists_RSF;

    global $current_rsfa_index;

    logInfoMsg("GENERATION DES RSF");
    
    
    begin_trans();
    
    enable_index("i_rsf_total_3");
    

    $nb = 0;
    $nbW = 0;
    $nb_rsf = 0;
    $nbW_total = 0;
    $nbW_detail = 0;
    $nbW_lpp = 0;
    $nbW_ucd = 0;
    $nbW_actes = 0;
    $nbE = 0;
    
    
    get_rss_um("*setarray");

    
    commit_trans();
    
    // Exécutants
    $actmed_array = array();
    
    $actesM_array = array();
	
    logDebugMsg("ACTMED FILE : $file_ACTMED");
	
    $handle = @fopen($file_ACTMED, "r");
    if ($handle) {
        while (!feof($handle)) {
            $buffer = fgets($handle, 99999);
            
            if (trim($buffer) != "" ) {

                $BUF_record = read_actmed_line($buffer);
                
                if ($BUF_record["type_enregistrement"] == "ACTMED") {
                
                    $cle = get_numrss($BUF_record["no_rss"]) . $BUF_record["code_acte"] . get_date_AAAAMMJJ($BUF_record["date_acte"]) . $BUF_record["activite_ccam"] ;
                    $actmed_array[$cle] = $BUF_record["code_medecin"];
                    
                    $cle = get_numrss($BUF_record["no_rss"]) . $BUF_record["code_acte"] . "00000000" . $BUF_record["activite_ccam"];
                    $actmed_array[$cle] = $BUF_record["code_medecin"];
                    
                    // cas particulier actes anesthésie en activite 1
                    if ($BUF_record["activite_ccam"] == "4") {
                        $gen1 = FALSE;
                        if ($BUF_record["code_acte"] == "AFLB010") {
                            $gen1 = TRUE;
                        }
                        if ($BUF_record["code_acte"] == "GELE001") {
                            $gen1 = TRUE;
                        }
                        if ($BUF_record["code_acte"] == "YYYY003") {
                            $gen1 = TRUE;
                        }
                        if ($BUF_record["code_acte"] == "YYYY004") {
                            $gen1 = TRUE;
                        }
                        if ($BUF_record["code_acte"] == "YYYY015") {
                            $gen1 = TRUE;
                        }
                        if ($BUF_record["code_acte"] == "YYYY020") {
                            $gen1 = TRUE;
                        }
                        if ($BUF_record["code_acte"] == "YYYY041") {
                            $gen1 = TRUE;
                        }
                        if ($BUF_record["code_acte"] == "YYYY044") {
                            $gen1 = TRUE;
                        }
                        if ($BUF_record["code_acte"] == "YYYY108") {
                            $gen1 = TRUE;
                        }
                        if ($BUF_record["code_acte"] == "YYYY118") {
                            $gen1 = TRUE;
                        }
                        if ($BUF_record["code_acte"] == "ZZLP008") {
                            $gen1 = TRUE;
                        }
                        if ($BUF_record["code_acte"] == "ZZLP012") {
                            $gen1 = TRUE;
                        }
                        if ($BUF_record["code_acte"] == "ZZLP025") {
                            $gen1 = TRUE;
                        }
                        if ($BUF_record["code_acte"] == "ZZLP030") {
                            $gen1 = TRUE;
                        }
                        if ($BUF_record["code_acte"] == "ZZLP042") {
                            $gen1 = TRUE;
                        }
                        if ($BUF_record["code_acte"] == "ZZLP054") {
                            $gen1 = TRUE;
                        }
                        if ($gen1 == TRUE) {
                            $cle = get_numrss($BUF_record["no_rss"]) . $BUF_record["code_acte"] . get_date_AAAAMMJJ($BUF_record["date_acte"]) . "1";
                            $actmed_array[$cle] = $BUF_record["code_medecin"];
                            
                            $cle = get_numrss($BUF_record["no_rss"]) . $BUF_record["code_acte"] . "00000000" . "1";
                            $actmed_array[$cle] = $BUF_record["code_medecin"];
                        }
                    }
                
                }

            }
        
        }
        
        fclose($handle);
    
    }
    
    $sqlcmd_exec = "";
    
    
    // prestation RSS public
    if ($file_exists_RSF && $ENV_TYPEETS != "1") {
        $current_rsfa_index = 0;
        
        $handle = @fopen($file_RSF, "r");
        if ($handle) {
            while (!feof($handle)) {
                $buffer = fgets($handle, 99999);
                
                if (trim($buffer) != "" ) {

                    $BUF_record = read_rsf_partial_line($buffer);
                    
                    if ($BUF_record["ok"] == TRUE) {

                        // ENTETE RSF
                        if ($BUF_record["type_enregistrement"] == "A") {
                        
                            if (get_numrss($BUF_record["no_rss"]) == 0) {
                                // $BUF_record["no_rss"] = $BUF_record["no_facture"] + 99000000000;
                                $BUF_record["no_rss"] = '9' . str_pad(ltrim($BUF_record["no_facture"], '0'), 8, '0', STR_PAD_LEFT);
                            }
                            
                            // RSS
                            if (controle_check_num($BUF_record["no_rss"],0,FALSE,$erreur,$commentaire)) {
                                $no_rss = get_numrss($BUF_record["no_rss"]);
                            }

                        }
                        
                        
                    }
                    
                }
                
            }
            
        }
    }
    
    $sqlcmd_insert_rsf = "INSERT INTO temp.p_rsf_total( 
                            rss_id,
                            finess,
                            no_rss,
                            code_pec,
                            rang_beneficiaire,
                            regime,
                            nature_pec,
                            justificatif_exo,
                            no_facture,
                            code_regularisation,
                            base_remboursement,
                            sejour_facture,
                            sejour_remboursable,
                            honoraires_factures,
                            honoraires_remboursable,
                            t2a_facture,
                            dmi_facture,
                            phc_facture,
                            participation_assure_avant_oc,
                            sejour_remboursable_2,
                            honoraires_remboursable_2,
                            montant_dmi_ghs2006,
                            forfait_facture,
                            nb_exh,
                            ca_exh,
                            nb_exb,
                            ca_exb,
                            nb_ghs,
                            ca_ghs,
                            taux_remboursement,
                            matricule_assure,
                            cle_matricule_assure,
                            pat_benef_cmu,
                            valorise_fides,
                            no_facture_sejour_mere,
                            exoneration_tm_id,
                            regime_id,
                            nature_pec_id,
                            code_pec_id,
                            type_contrat_oc_id,
                            motif_non_facturation_id,
                            code_gestion,
                            no_organisme_complementaire,
                            no_at_date_adc,
                            nb_ghsmin,
                            montant_total_sejour_patient,
                            nb_rejet_amo,
                            date_facture_amo,
                            date_facture_amc,
                            date_facture_patient,
                            date_paiement_amo,
                            date_paiement_amc,
                            date_paiement_patient,
                            statut_ft_amo,
                            statut_ft_amc,
                            statut_ft_patient,
                            pays_amo,
                            no_ligne,
                            no_ipp)";
    
    
    $sqlcmd_insert_prestation = "INSERT INTO temp.p_rsf_detail( 
                            rss_id,  
                            finess,  
                            no_rss,  
                            nature,  
                            mt,  
                            dmt,  
                            date_debut,  
                            date_fin,  
                            nombre,  
                            coefficient,  
                            prix_unitaire,  
                            base_remboursement,  
                            base_remboursement_sauf_transition,
                            taux_remboursement,  
                            sejour_facture,  
                            sejour_remboursable,  
                            compteur,  
                            ligne_t2a,  
                            pec_fj,  
                            pec_fj_id,  
                            coefficient_mco,  
                            sejour_remboursable_2,  
                            ghs_id,  
                            sejour_rembourse_noemie,  
                            nature_noemie,  
                            prestation_id, 
                            type, 
                            coefficient_geo, 
                            est_ligne_rss, 
                            est_ligne_rum, 
                            no_rum, 
                            unite_medicale_id, 
                            base_remboursement_rum,
                            type_uf_consultation_id,
                            no_ligne) ";
    
    $sqlcmd_insert_lpp = "INSERT INTO temp.p_rss_lpp( ";
    $sqlcmd_insert_lpp = $sqlcmd_insert_lpp . "rss_id,  ";
    $sqlcmd_insert_lpp = $sqlcmd_insert_lpp . "finess, ";
    $sqlcmd_insert_lpp = $sqlcmd_insert_lpp . "no_rss, ";
    $sqlcmd_insert_lpp = $sqlcmd_insert_lpp . "rang, ";
    $sqlcmd_insert_lpp = $sqlcmd_insert_lpp . "date_lpp, ";
    $sqlcmd_insert_lpp = $sqlcmd_insert_lpp . "lpp_id, ";
    $sqlcmd_insert_lpp = $sqlcmd_insert_lpp . "nombre, ";
    $sqlcmd_insert_lpp = $sqlcmd_insert_lpp . "prix_unitaire, ";
    $sqlcmd_insert_lpp = $sqlcmd_insert_lpp . "montant_facture,";
    $sqlcmd_insert_lpp = $sqlcmd_insert_lpp . "non_pris_en_compte";
    $sqlcmd_insert_lpp = $sqlcmd_insert_lpp . ") ";
    

    $sqlcmd_insert_ucd = "INSERT INTO temp.p_rss_ucd(
            finess, no_rss, rang, date_ucd, ucd_id, nombre, coefficient_fractionnement, 
            prix_unitaire_achat, prix_unitaire_ecart_indemnisable, montant_ecart_indemnisable, 
            montant_facture, rss_id, non_pris_en_compte, type_ucd_id, indication) ";
    
    $sqlcmd_insert_acte = "INSERT INTO temp.p_rss_actes(";
    $sqlcmd_insert_acte = $sqlcmd_insert_acte . "rss_id,  ";
    $sqlcmd_insert_acte = $sqlcmd_insert_acte . "finess, ";
    $sqlcmd_insert_acte = $sqlcmd_insert_acte . "no_rss, ";
    $sqlcmd_insert_acte = $sqlcmd_insert_acte . "no_rum, ";
    $sqlcmd_insert_acte = $sqlcmd_insert_acte . "unite_medicale, ";
    $sqlcmd_insert_acte = $sqlcmd_insert_acte . "unite_medicale_id, ";
    $sqlcmd_insert_acte = $sqlcmd_insert_acte . "date_acte, ";
    $sqlcmd_insert_acte = $sqlcmd_insert_acte . "medecin_id, ";
    $sqlcmd_insert_acte = $sqlcmd_insert_acte . "acte_id, ";
	$sqlcmd_insert_acte = $sqlcmd_insert_acte . "acte_ccam_descriptif_id, ";
    $sqlcmd_insert_acte = $sqlcmd_insert_acte . "nombre, ";
    $sqlcmd_insert_acte = $sqlcmd_insert_acte . "phase_ccam, ";
    $sqlcmd_insert_acte = $sqlcmd_insert_acte . "activite_ccam, ";
    $sqlcmd_insert_acte = $sqlcmd_insert_acte . "extension_ccam, ";
    $sqlcmd_insert_acte = $sqlcmd_insert_acte . "modificateur_ccam_1, ";
    $sqlcmd_insert_acte = $sqlcmd_insert_acte . "modificateur_ccam_2, ";
    $sqlcmd_insert_acte = $sqlcmd_insert_acte . "modificateur_ccam_3, ";
    $sqlcmd_insert_acte = $sqlcmd_insert_acte . "modificateur_ccam_4, ";
    $sqlcmd_insert_acte = $sqlcmd_insert_acte . "remboursement_excp_ccam, ";
    $sqlcmd_insert_acte = $sqlcmd_insert_acte . "association_nonprevue_ccam";
    $sqlcmd_insert_acte = $sqlcmd_insert_acte . ") ";
    
    $sqlcmd_insert_transfert = "INSERT INTO temp.p_rss_transferts(
            rss_id, etablissement_provenance_id, etablissement_destination_id) ";
    
    
    // Génération
    $no_ligne = 0;
    $no_ligne_a = 0;
    $rss_id = 0;
    
    $nblpp = 0;
    $nbucd = 0;
    
    $last_no_rss = -1;
    $inserted_rsf_array = array();

    $current_rsfa_index = 0;
    $handle = @fopen($file_RSF, "r");
    if ($handle) {
        while (!feof($handle)) {
            $buffer = fgets($handle, 99999);
            
            $no_ligne++;
            if (trim($buffer) != "" && $no_ligne < 10000000000) {
            
                $nb++;
                
                $BUF_record = read_rsf_line($buffer);
                
                if ($BUF_record["ok"] == TRUE) {
                
                    // ENTETE RSF
                    if ($BUF_record["type_enregistrement"] == "A") {
                    
                        if (strlen($sqlcmd_exec) > 64000) {
                            $toResult = execute_sql($sqlcmd_exec, $nbE, $nbW_actesxx );
                            $sqlcmd_exec = "";
                        }
                    
                        $positif = true;
                        $no_ligne_a++;
                    
                        $rss_id = 0;
                        if (get_numrss($BUF_record["no_rss"]) == 0) {
                            // $BUF_record["no_rss"] = $BUF_record["no_facture"] + 99000000000;
                            $BUF_record["no_rss"] = '9' . str_pad(ltrim($BUF_record["no_facture"], '0'), 8, '0', STR_PAD_LEFT);
                        }
                        
                        $no_rss = get_numrss($BUF_record["no_rss"]);
                        
                        
                        
                    
                        $rsf_ok = TRUE;
                                                
                        if ($rsf_ok == TRUE) {
                        
                            $nature_operation = trim($BUF_record["nature_operation"]);
                            if ($nature_operation == "5") {
                                $positif = false;
                            }
                        
                            $nb_rsf++;
                        
                            $finess = $BUF_record["finess"];
                            
                            $code_pec = $BUF_record["code_pec"];    // deprecated, remplacé par code_pec_id
                            if ($ENV_TYPEETS == "1" && $code_pec != "1" && $code_pec != "2" && $code_pec != "3" && $code_pec != "4" && $code_pec != "5" ) {
                                $code_pec = "1";
                            }
                            if ($ENV_TYPEETS != "1" && $code_pec != "0" && $code_pec != "1" && $code_pec != "2" && $code_pec != "3" && $code_pec != "X" ) {
                                $code_pec = "1";
                            }
                            $code_pec_id = get_pec($code_pec);
                            
                            $rang_beneficiaire = $BUF_record["rang_beneficiaire"];
                            $regime = $BUF_record["grand_regime"];  // deprecated, remplacé par regime_id
                            $regime_id = get_regime($BUF_record["grand_regime"]);
                            $nature_pec = $BUF_record["nature_assurance"];  // deprecated, remplacé par nature_pec_id
                            if (! controle_check_num($nature_pec,2, FALSE,$none,$none)) {
                                $nature_pec = "10";
                            }
                            $nature_pec_id = get_nature_pec($nature_pec);
                            $matricule_assure = toSQL($BUF_record["immatriculation_assure"]) ;
                            $cle_matricule_assure = $BUF_record["cle_immatriculation_assure"] ;
                            $justificatif_exo = $BUF_record["justificatif_exo"];    // deprecated, remplacé par exoneration_tm_id
                            $exoneration_tm_id = get_exoneration_tm($BUF_record["justificatif_exo"]);
                            $no_facture = get_num($BUF_record["no_facture"]);
                            $code_regularisation = $BUF_record["nature_operation"]; 
                            if ($code_regularisation != "1" && $code_regularisation != "2" && $code_regularisation != "3" && $code_regularisation != "4" && $code_regularisation != "5" && $code_regularisation != "9" ) {
                                $code_regularisation = "1";
                            }
                            $motif_non_facturation_id = get_motif_non_facturation($BUF_record["motif_non_facturation"]);
                            $type_contrat_oc_id = get_type_contrat_oc($BUF_record["type_contrat_oc"]); 
                            $base_remboursement = get_num($BUF_record["base_remboursement_c"]) / 100;
                            $sejour_facture = get_num($BUF_record["base_remboursement_c"]) / 100; 
                            $sejour_remboursable = 0; 
                            $honoraires_factures = get_num($BUF_record["total_honoraires_factures"]) / 100;  
                            $honoraires_remboursable = get_num($BUF_record["total_honoraires_remboursable"]) / 100;   
                            $t2a_facture = 0;
                            $dmi_facture = 0;
                            $phc_facture = 0;
                            $participation_assure_avant_oc = get_num($BUF_record["total_assure_avant_oc"]) / 100;    
                            $no_ipp = floatval($BUF_record["no_ipp"]);
                            $sejour_remboursable_2 = 0;
                            $honoraires_remboursable_2 = 0; 
                            $montant_dmi_ghs2006 = 0;
                            $forfait_facture = 0;
                            $nb_exh = 0;
                            $ca_exh = 0;
                            $nb_exb = 0;
                            $ca_exb = 0;
                            $nb_ghs = 0;
                            $ca_ghs = 0;
                            $nb_ghsmin = 0;
                            
                            // Normalement, dans le standard, seules les valeurs 0 ou 1 sont autorisées mais SIGEMS
                            // utilise O (oui) et N (non)
                            $pat_benef_cmu = $BUF_record["pat_benef_cmu"];
                            if ($pat_benef_cmu == "O" || $pat_benef_cmu == "1") {
                                $pat_benef_cmu = 1;
                            }
                            else if ($pat_benef_cmu == "N" || $pat_benef_cmu == "0") {
                                $pat_benef_cmu = 0;
                            }
                            else {
                                $pat_benef_cmu = 'null';    // valeur par défaut si erreur de codage
                            }
                            // Idem pour valorise_fides
                            $valorise_fides = $BUF_record["valorise_fides"];
                            if ($valorise_fides == "O" || $valorise_fides == "1") {
                                $valorise_fides = 1;
                            }
                            else if ($valorise_fides == "N" || $valorise_fides == "0") {
                                $valorise_fides = 0;
                            }
                            else {
                                $valorise_fides = 'null';   // valeur par défaut si erreur de codage
                            }
                            
                            if (strlen($BUF_record["no_facture_sejour_mere"]) == 0)
                                $no_facture_sejour_mere = "";
                            else
                                $no_facture_sejour_mere = $BUF_record["no_facture_sejour_mere"];
                            
                            $date_entree_rsf = sqlDate($BUF_record["date_entree"]);
                            $no_organisme_complementaire = $BUF_record["no_organisme_complementaire"];
                            $no_at_date_adc = $BUF_record["no_at_date_adc"];
                            
                            $code_gestion = $BUF_record["code_gestion"];
                            
                            // nouveautés 2018
                            $montant_total_sejour_patient = get_num($BUF_record["montant_total_sejour_patient"]) / 100;
                            $nb_rejet_amo = get_num($BUF_record["nb_rejet_amo"]);
                            $date_facture_amo = get_date_or_null($BUF_record["date_facture_amo"]);
                            $date_facture_amc = get_date_or_null($BUF_record["date_facture_amc"]);
                            $date_facture_patient = get_date_or_null($BUF_record["date_facture_patient"]);
                            $date_paiement_amo = get_date_or_null($BUF_record["date_paiement_amo"]);
                            $date_paiement_amc = get_date_or_null($BUF_record["date_paiement_amc"]);
                            $date_paiement_patient = get_date_or_null($BUF_record["date_paiement_patient"]);
                            $statut_ft_amo = $BUF_record["statut_ft_amo"];
                            $statut_ft_amc = $BUF_record["statut_ft_amc"];
                            $statut_ft_patient = $BUF_record["statut_ft_patient"];
                            $pays_amo = $BUF_record["pays_amo"];
                            
                            $rss_id = get_rss($no_rss);
							
							
                            //if($rss_id === '483612') {
                                //echo "\r\n" . date("d/m/Y H:i:s") . "\t" . "DEBUG" . "\t" . "DATE PAIEMENT AMO BEFORE : " . $BUF_record["date_paiement_amo"];
                              //  echo "\r\n" . date("d/m/Y H:i:s") . "\t" . "DEBUG" . "\t" . "DATE PAIEMENT AMO AFTER : " . $date_paiement_amo;
                            //}
                            
                            // OID rss
                            
                            if ($positif == false) {
                                $base_remboursement = 0 - $base_remboursement; 
                                $sejour_facture = 0 - $sejour_facture; 
                                $honoraires_factures =  0 - $honoraires_factures;
                                $honoraires_remboursable =  0 - $honoraires_remboursable;
                                $participation_assure_avant_oc =  0 - $participation_assure_avant_oc;
                            }
                            
                            if ($rss_id > 0) {
                            
                                // Création RSF total
                                if ($no_rss != $last_no_rss) {
                                    $inserted_rsf = @$inserted_rsf_array[$no_rss] + 0;
                                    if ($inserted_rsf == 0) {
                                        $sqlcmd = "$sqlcmd_insert_rsf VALUES( $rss_id,  '$finess',  $no_rss,  '$code_pec',  '$rang_beneficiaire',  '$regime', '$nature_pec',  
                                            '$justificatif_exo',  '$no_facture',  '$code_regularisation',  $base_remboursement, $sejour_facture,  $sejour_remboursable,  
                                            $honoraires_factures,  $honoraires_remboursable,  $t2a_facture, $dmi_facture,  $phc_facture,  $participation_assure_avant_oc,  
                                            $sejour_remboursable_2,  $honoraires_remboursable_2, $montant_dmi_ghs2006,  $forfait_facture,  
                                            $nb_exh,  $ca_exh,  $nb_exb,  $ca_exb,  $nb_ghs,  $ca_ghs, 100, '$matricule_assure', '$cle_matricule_assure',
                                            $pat_benef_cmu, $valorise_fides, '$no_facture_sejour_mere', $exoneration_tm_id, $regime_id, $nature_pec_id, $code_pec_id, $type_contrat_oc_id, $motif_non_facturation_id, '$code_gestion',
                                            '$no_organisme_complementaire', '$no_at_date_adc', $nb_ghsmin,
                                            $montant_total_sejour_patient, $nb_rejet_amo,
                                            $date_facture_amo, $date_facture_amc, $date_facture_patient,
                                            $date_paiement_amo, $date_paiement_amc, $date_paiement_patient,
                                            '$statut_ft_amo', '$statut_ft_amc', '$statut_ft_patient',
                                            '$pays_amo', $no_ligne_a, $no_ipp) ";
                                    }
                                    else {
                                        $no_ligne_a--;
                                        $sqlcmd = "UPDATE temp.p_rsf_total SET 
                                                base_remboursement = base_remboursement + $base_remboursement, 
                                                sejour_facture = sejour_facture + $sejour_facture, 
                                                sejour_remboursable = sejour_remboursable + $sejour_remboursable, 
                                                honoraires_factures = honoraires_factures + $honoraires_factures, 
                                                honoraires_remboursable = honoraires_remboursable + $honoraires_remboursable 
                                            WHERE rss_id = $rss_id ";
                                    }
                                    $last_no_rss = $no_rss;
                                    $inserted_rsf_array[$no_rss] = $no_rss;
                                }
                                
                                else {
                                    $no_ligne_a--;
                                    $sqlcmd = " UPDATE temp.p_rsf_total SET
                                                    base_remboursement = base_remboursement + $base_remboursement, 
                                                    sejour_facture = sejour_facture + $sejour_facture, 
                                                    sejour_remboursable = sejour_remboursable + $sejour_remboursable, 
                                                    honoraires_factures = honoraires_factures + $honoraires_factures, 
                                                    honoraires_remboursable = honoraires_remboursable + $honoraires_remboursable 
                                                WHERE rss_id = $rss_id ";
                                }
                                $sqlcmd_exec = "$sqlcmd_exec$sqlcmd;";
                                $nbW_total++;
                                //$toResult = execute_sql($sqlcmd, $nbE, $nbW_total );
                            }
                            else {
                                logInfoMsg($no_rss . "\tPas d'ajout dans RSF TOTAL");
                            }
                        }
                    }
                    
                    // RSF B
                    if ($BUF_record["type_enregistrement"] == "B" && $rss_id > 0) {
                        
                        $finess = $BUF_record["finess"];
                        $no_rss = get_numrss($BUF_record["no_rss"]);
                        $nature = "";
                        $mt = $BUF_record["mode_traitement"]; 
                        if (! controle_check_num($mt,2, TRUE,$none,$none)) {
                            $mt = "";
                        }
                        $dmt = $BUF_record["discpline_prestation"];
                        if (! controle_check_num($mt,3, TRUE,$none,$none)) {
                            $dmt = "";
                        }
                        $date_debut = sqlDate($BUF_record["date_debut"]);
                        $date_fin = sqlDate($BUF_record["date_fin"]); 
                        $nombre= get_num($BUF_record["nombre"],1);
                        $coefficient = get_num($BUF_record["coefficient"],100) / 100;     
                        $prix_unitaire = get_num($BUF_record["prix_unitaire"]) / 100;      
                        $base_remboursement = get_num($BUF_record["base_remboursement"]) / 100;    
                        $taux_remboursement = get_num($BUF_record["taux"], 100) ;
                        $sejour_facture = get_num($BUF_record["montant_total_depense"]) / 100;  
                        $sejour_remboursable = get_num($BUF_record["montant_remboursable"]) / 100;  
                        $compteur = "";
                        $ligne_t2a = "";
                        $pec_fj = $BUF_record["code_pec_fj"];   // deprecated, remplacé par code_pec_fj_id
                        $pec_fj_id = get_pec_fj($BUF_record["code_pec_fj"]);
                        $coefficient_mco = get_num($BUF_record["coefficient_mco"], 10000) / 10000;     
                        $sejour_remboursable_2 = 0;
                        $ghs_id = 0;
                        $sejour_rembourse_noemie = get_num($BUF_record["montant_remboursé_noemie"]) / 100;    
                        $nature_noemie = $BUF_record["nature_noemie"]; 
                        $prestation_id = 0;
                        
                        $ghs_id = get_ghs($BUF_record["no_ghs"]);
                        
                        $prestation_id = get_prestation($BUF_record["code_acte"]);
                        
                        if ($positif == false) {
                            $nombre = 0 - $nombre; 
                            $base_remboursement = 0 - $base_remboursement; 
                            $sejour_facture = 0 - $sejour_facture; 
                            $sejour_remboursable = 0 - $sejour_remboursable; 
                            $honoraires_factures =  0 - $honoraires_factures;
                            $honoraires_remboursable =  0 - $honoraires_remboursable;
                            $sejour_rembourse_noemie =  0 - $sejour_rembourse_noemie;
                        }
                        
                        $sqlcmd = "$sqlcmd_insert_prestation VALUES($rss_id,  '$finess',  $no_rss,  '$nature',  '$mt',  '$dmt',  '$date_debut', '$date_fin',  
                            $nombre,  $coefficient,  $prix_unitaire,  $base_remboursement,  $base_remboursement,  $taux_remboursement, $sejour_facture,  
                            $sejour_remboursable,  '$compteur',  '$ligne_t2a',  '$pec_fj',  '$pec_fj_id',  $coefficient_mco, $sejour_remboursable_2,  
                            $ghs_id,  $sejour_rembourse_noemie,  '$nature_noemie',  $prestation_id, 'B' , 
                            1,  '1', '0', 0, 0, 0, 0, $no_ligne
                            ) ";
                        $sqlcmd_exec = "$sqlcmd_exec$sqlcmd;";
                        $nbW_detail++;
                        //$toResult = execute_sql($sqlcmd, $nbE, $nbW_detail );
                        
                        // SI GHS, mise à jour RSF
                        if ($BUF_record["code_acte"] == "GHS") {
                            if ($ghs_code < 5800 || $ghs_code > 5840) {
                                $sqlcmd = "UPDATE temp.p_rss SET ghs_id = '$ghs_id' WHERE oid = $rss_id AND ghs_id = 0 ";
                                
                                //$toResult = execute_sql($sqlcmd, $nbE, $nbW );
                            }
                        }
                        if ($BUF_record["code_acte"] == "EXH") {
                            if ($ghs_code < 5800 || $ghs_code > 5840) {
                                $sqlcmd = "UPDATE temp.p_rss SET ghs_id = '$ghs_id' WHERE oid = $rss_id AND ghs_id = 0";
                                $sqlcmd_exec = "$sqlcmd_exec$sqlcmd;";
                                //$toResult = execute_sql($sqlcmd, $nbE, $nbW );
                            }
                        }
                    }
                    
                    // RSF C
                    if ($BUF_record["type_enregistrement"] == "C" && $rss_id > 0) {
                        
                        $finess = $BUF_record["finess"];
                        $no_rss = get_numrss($BUF_record["no_rss"]);
                        $nature = "";
                        $mt = $BUF_record["mode_traitement"]; 
                        if (! controle_check_num($mt,2, TRUE,$none,$none)) {
                            $mt = "";
                        }
                        $dmt = $BUF_record["discpline_prestation"];
                        if (! controle_check_num($mt,3, TRUE,$none,$none)) {
                            $dmt = "";
                        }
                        $date_debut = sqlDate($BUF_record["date_debut"]);
                        $date_fin = sqlDate($BUF_record["date_fin"]); 
                        $nombre= get_num($BUF_record["nombre"],1);
                        $coefficient = get_num($BUF_record["coefficient"],100) / 100;     
                        $prix_unitaire = get_num($BUF_record["prix_unitaire"]) / 100;      
                        $base_remboursement = get_num($BUF_record["base_remboursement"]) / 100;    
                        $taux_remboursement = get_num($BUF_record["taux"], 100) ;
                        $sejour_facture = get_num($BUF_record["montant_total_depense"]) / 100;  
                        $sejour_remboursable = get_num($BUF_record["montant_remboursable"]) / 100;  
                        $compteur = "";
                        $ligne_t2a = "";
                        $pec_fj = $BUF_record["code_pec_fj"];   // deprecated, remplacé par pec_fj_id
                        $pec_fj_id = get_pec_fj($BUF_record["code_pec_fj"]);
                        $coefficient_mco = get_num($BUF_record["coefficient_mco"], 10000) / 10000;     
                        $sejour_remboursable_2 = 0;
                        $ghs_id = 0;
                        $sejour_rembourse_noemie = get_num($BUF_record["montant_remboursé_noemie"]) / 100;    
                        $nature_noemie = $BUF_record["nature_noemie"]; 
                        $prestation_id = 0;
                        
                        $ghs_id = get_ghs($BUF_record["no_ghs"]);

                        $prestation_id = get_prestation($BUF_record["code_acte"]);
                        
                        $type_uf_consultation_id = get_type_uf_consultation($BUF_record["type_uf_consultation"]);
                        
                        if ($positif == false) {
                            $nombre = 0 - $nombre; 
                            $base_remboursement = 0 - $base_remboursement; 
                            $sejour_facture = 0 - $sejour_facture; 
                            $sejour_remboursable = 0 - $sejour_remboursable; 
                            $honoraires_factures =  0 - $honoraires_factures;
                            $honoraires_remboursable =  0 - $honoraires_remboursable;
                            $sejour_rembourse_noemie =  0 - $sejour_rembourse_noemie;
                        }
                        
                        $type_bc = "C";
                        if ($BUF_record["code_acte"] == "SE1" || 
                            $BUF_record["code_acte"] == "SE2" || 
                            $BUF_record["code_acte"] == "SE3" || 
                            $BUF_record["code_acte"] == "SE4" || 
                            $BUF_record["code_acte"] == "SE5" || 
                            $BUF_record["code_acte"] == "SE6" ||       
							$BUF_record["code_acte"] == "SE7" ||      							
                            $BUF_record["code_acte"] == "ATU" || 
                            $BUF_record["code_acte"] == "FFM" ||
                            $BUF_record["code_acte"] == "APE" ||
                            $BUF_record["code_acte"] == "AP2" ||
                            $BUF_record["code_acte"] == "FPI" ||
                            ($BUF_record["code_acte"] == "FSD" && $ENV_OPTPMSI_FSD_B == "1")) {
                            
                                $type_bc = "B";
                        }
                        
                        $sqlcmd = "$sqlcmd_insert_prestation VALUES($rss_id,  '$finess',  $no_rss,  '$nature',  '$mt',  '$dmt',  '$date_debut', '$date_fin',  
                            $nombre,  $coefficient,  $prix_unitaire,  $base_remboursement,  $base_remboursement,  $taux_remboursement, $sejour_facture,  $sejour_remboursable,  
                            '$compteur',  '$ligne_t2a',  '$pec_fj',  '$pec_fj_id',  $coefficient_mco, $sejour_remboursable_2,  $ghs_id,  $sejour_rembourse_noemie,  
                            '$nature_noemie',  $prestation_id, '$type_bc', 
                            1,  '1', '0', 0, 0, 0, $type_uf_consultation_id, $no_ligne) ";
                        $sqlcmd_exec = "$sqlcmd_exec$sqlcmd;";
                        $nbW_detail++;
                        
                    }
                    
                    // RSF P (LPP)
                    if ($BUF_record["type_enregistrement"] == "P" && $rss_id > 0) {
                    
                        $nblpp++;
                        
                        if ($rss_id > 0) {

                            $finess = $BUF_record["finess"];
                            $no_rss = get_numrss($BUF_record["no_rss"]);
                            $rang = ""; 
                            $date_lpp = sqlDate($BUF_record["date_debut"]); 
                            if (!controle_check_date($BUF_record["date_debut"],$none,$none)) {
                                $date_lpp = $date_entree_rsf;
                            }
                            $lpp_id = 0;
                            $nombre = get_num($BUF_record["nombre"],1); 
                            $prix_unitaire = get_num($BUF_record["prix_unitaire"]) / 100;      
                            $montant_facture = get_num($BUF_record["montant_facture"]) / 100;      


                            $lpp_id = get_lpp($BUF_record["code_lpp"]);
                            
                            if ($positif == false) {
                                $nombre = 0 - $nombre; 
                                $montant_facture = 0 - $montant_facture; 
                                $sejour_facture = 0 - $sejour_facture; 
                            }
                            
                            $sqlcmd = "$sqlcmd_insert_lpp VALUES( $rss_id,  '$finess',  $no_rss,  '$rang', '$date_lpp', $lpp_id, $nombre, $prix_unitaire, $montant_facture, '0') ";
                            $sqlcmd_exec = "$sqlcmd_exec$sqlcmd;";
                            $nbW_lpp++; 
                            //$toResult = execute_sql($sqlcmd, $nbE, $nbW_lpp );
                            
                            if (get_num($BUF_record["nombre_2"]) > 0) {
                            
                                $lpp_id = 0;
                                $nombre = get_num($BUF_record["nombre_2"]); 
                                $prix_unitaire = get_num($BUF_record["prix_unitaire_2"]) / 100;      
                                $montant_facture = get_num($BUF_record["montant_facture_2"]) / 100;      

                                $lpp_id = get_lpp($BUF_record["code_lpp_2"]);
                                
                                if ($positif == false) {
                                    $nombre = 0 - $nombre; 
                                    $montant_facture = 0 - $montant_facture; 
                                    $sejour_facture = 0 - $sejour_facture; 
                                }
                                
                                $sqlcmd = "$sqlcmd_insert_lpp VALUES( $rss_id,  '$finess',  $no_rss,  '$rang', '$date_lpp', $lpp_id, $nombre, $prix_unitaire, $montant_facture, '0') ";
                                $sqlcmd_exec = "$sqlcmd_exec$sqlcmd;";
                                $nbW_lpp++; 
                                
                            }
                        }
                    }
                    
                    // RSF H (UCD)
                    if ($BUF_record["type_enregistrement"] == "H" && $rss_id > 0) {
                    
                        $nbucd++;
                        
                        if ($rss_id > 0) {

                            $finess = $BUF_record["finess"];
                            $no_rss = get_numrss($BUF_record["no_rss"]);
                            $rang = ""; 
                            $date_ucd = sqlDate($BUF_record["date_debut"]); 
                            if (!controle_check_date($BUF_record["date_debut"],$none,$none)) {
                                $date_ucd = $date_entree_rsf;
                            }
                            $ucd_id = 0;
                            $nombre = get_num($BUF_record["nombre"],1); 
                            $coefficient_fractionnement = get_num($BUF_record["coefficient_fractionnement"]) / 10000;     
                            if ($coefficient_fractionnement == 0) {
                                $coefficient_fractionnement = 1;
                            }
                            $prix_unitaire_achat = get_num($BUF_record["prix_unitaire_achat"]) / 100;  
                            $prix_unitaire_ecart_indemnisable = get_num($BUF_record["prix_unitaire_ecart_indemnisable"]) / 100;  
                            $montant_ecart_indemnisable = get_num($BUF_record["montant_ecart_indemnisable"]) / 100;  
                            
                            $montant_facture = get_num($BUF_record["montant_facture"]) / 100;      
                            $indication = $BUF_record["indication"];


                            $ucd_id = get_ucd($BUF_record["code_ucd"]);
                            $type_ucd_id = get_type_ucd("SUS");
                            
                            if ($positif == false) {
                                $nombre = 0 - $nombre; 
                                $montant_facture = 0 - $montant_facture; 
                                $sejour_facture = 0 - $sejour_facture; 
                            }
                            
                            $sqlcmd = "$sqlcmd_insert_ucd VALUES( '$finess', $no_rss, '$rang', '$date_ucd', $ucd_id, $nombre, 
                                $coefficient_fractionnement, $prix_unitaire_achat, $prix_unitaire_ecart_indemnisable, 
                                $montant_ecart_indemnisable, $montant_facture, $rss_id, '0', $type_ucd_id, upper('$indication'))";
                            $sqlcmd_exec = "$sqlcmd_exec$sqlcmd;";
                            $nbW_ucd++; 

                        }
                    }
                    
                    // RSF M actes
                    if ($BUF_record["type_enregistrement"] == "M" && $rss_id > 0) {

                        $finess = $BUF_record["finess"];
                        $no_rss = get_numrss($BUF_record["no_rss"]);

                    
                        $BUF_code_acte = trim($BUF_record["code_acte"]);
                        $acte_id = get_acte($BUF_code_acte);
                        
                        $date_acte = sqlDate($BUF_record["date_acte"]);
                        if (!controle_check_date($BUF_record["date_acte"],$none,$none)) {
                            $date_acte = $date_entree_rsf;
                        }
                        
                        $phase_ccam = trim($BUF_record["phase_ccam"]);
                        $activite_ccam = trim($BUF_record["activite_ccam"]);
                        if (! controle_check_num($activite_ccam,1, FALSE,$none,$none)) {
                            $activite_ccam = "1";
                        }
                        $extension_ccam = trim($BUF_record["extension_ccam"]);
                        $modificateur_ccam_1 = trim($BUF_record["modificateur_ccam_1"]);
                        $modificateur_ccam_2 = trim($BUF_record["modificateur_ccam_2"]);
                        $modificateur_ccam_3 = trim($BUF_record["modificateur_ccam_3"]);
                        $modificateur_ccam_4 = trim($BUF_record["modificateur_ccam_4"]);
                        $remboursement_excp_ccam = trim($BUF_record["remboursement_excp_ccam"]);
                        $association_nonprevue_ccam = trim($BUF_record["association_nonprevue_ccam"]);
                        $nombre = 1;
                        $no_rum = 0;
                        
                        $medecin_id = 0;
                        
                        
                        // Medecin acte
                        $cle = get_numrss($BUF_record["no_rss"]) . $BUF_record["code_acte"] . get_date_AAAAMMJJ($BUF_record["date_acte"]) . $BUF_record["activite_ccam"];
                        $code_med = "";
                        if (isset($actmed_array[$cle])){
                            $code_med = $actmed_array[$cle];
                            if ($code_med === "") {
                                $cle = get_numrss($BUF_record["no_rss"]) . $BUF_record["code_acte"] . "00000000" . $BUF_record["activite_ccam"];
                                $code_med = $actmed_array[$cle];
                            }
                        }
                        if ($code_med != "") {
                            $medecin_id = get_medecin($code_med);
                        }
                        
                        $unite_medicale = "";
                        $unite_medicale_id = get_rss_um($rss_id);
                        if ($unite_medicale_id != 0) {
                            $no_rum = 1;
                        }
                        
                        if ($positif == false) {
                            $nombre = 0 - $nombre; 
                        }

                        $sqlcmd = "$sqlcmd_insert_acte VALUES( $rss_id,  '$finess',  $no_rss,  $no_rum,  '$unite_medicale', $unite_medicale_id, '$date_acte', $medecin_id, $acte_id, $acte_id, $nombre, '$phase_ccam', '$activite_ccam', '$extension_ccam', '$modificateur_ccam_1', '$modificateur_ccam_2', '$modificateur_ccam_3', '$modificateur_ccam_4', '$remboursement_excp_ccam', '$association_nonprevue_ccam') ";
                        $sqlcmd_exec = "$sqlcmd_exec$sqlcmd;";
                        $nbW_actes++;   
                        
                        $key = trim("$no_rss$BUF_code_acte$activite_ccam");
                        $actesM_array[$key] = "O";

					}
					
					// RSF I (transfert)
                    if ($BUF_record["type_enregistrement"] == "I" && $rss_id > 0) {
                    
                        $no_rss = get_num($BUF_record["no_rss"]);
                        $etablissement_provenance_id = 0;

                        // On récupère les séjours déjà présent dans p_rss_transfert qui ont un mode de sortie 7 ou 0
                        // Afin de garder l'etablissement de provenance
                        $sqlIsTransfert = "SELECT oid, COALESCE(etablissement_provenance_id,0) as prov_id
                                           FROM temp.p_rss
                                           JOIN temp.transferts_with_no_rss ON transferts_with_no_rss.no_rss = p_rss.no_rss
                                           WHERE mode_sortie IN (7, 0)
                                           AND p_rss.no_rss = $no_rss;
                                          ";

                        $isTransfert = $iCTI_connexion->query($sqlIsTransfert);
                        $res = pg_fetch_array($isTransfert);
                        if ($res != false){
                            $etablissement_provenance_id = $res["prov_id"];
                        }
                        $etablissement_destination_id = get_finess($BUF_record["finess_dest"]);
                        
                        $sqlcmd = "$sqlcmd_insert_transfert VALUES( $rss_id, COALESCE($etablissement_provenance_id, 0), COALESCE($etablissement_destination_id,0))";
                        $sqlcmd_exec = "$sqlcmd_exec$sqlcmd;";
                        $nbW_ucd++; 

                    }
                    
                }
			}
        }
        
        fclose($handle);
    
    }
    
    if ($sqlcmd_exec != "") {
        $toResult = execute_sql($sqlcmd_exec, $nbE, $nbW_actesxx );
        $sqlcmd_exec = "";
    }
    
    
    commit_trans();
    
    
    // Depuis M03 2019, le numero IPP est renseignable dans les RSF-ACE A. S'il l'est (différent de 0, valeur par défaut), on le met à jour dans les RSS
    logInfoMsg("IPP selon RSF-ACE-A");
    
    $sqlcmd = "UPDATE temp.p_rss SET 
                    no_patient = p_rsf_total.no_ipp
                FROM 
                    temp.p_rsf_total
                WHERE 1=1
                    AND p_rss.oid = p_rsf_total.rss_id
                    AND p_rsf_total.no_ipp != 0
                    AND p_rsf_total.no_ipp != p_rss.no_patient
                ; ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_lpp );
    commit_trans();

    // Compteurs
    $sqlcmd = "UPDATE pmsi.p_imports SET ";
    $sqlcmd = $sqlcmd . "nb_rsf = $nb_rsf ";
    $sqlcmd = $sqlcmd . "WHERE oid = $import_id";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    
    commit_trans();
    
    
    
    // Ajout des actes rss qui ne sont pas dans les RSF
    enable_index("i_rss_actes_2");
    enable_index("i_rss_actes_8");
    
    
    if ($ENV_TYPEETS == "1") {
        logInfoMsg("Actes RUM");
        
        
        $no_ligne = 0;
        
        $handle = @fopen($file_RSS, "r");
        if ($handle) {
            while (!feof($handle)) {
                $buffer = fgets($handle, 99999);
                
                $no_ligne++;
                if (trim($buffer) != "" && $no_ligne < 100000000000 ) {
                
                    $nb++;
                    
                    $BUF_record = read_rum_line($buffer);
                    
                    if ($BUF_record["type_enregistrement"] == "RUM") {
                    
                        if (strlen($sqlcmd_exec) > 64000) {
                            $toResult = execute_sql($sqlcmd_exec, $nbE, $nbW_actesxx );
                            $sqlcmd_exec = "";
                        }
                    
                        $no_rss = get_numrss($BUF_record["no_rss"]);
                        $no_rum = get_num($BUF_record["no_rum"]);
                        $unite_medicale = $BUF_record["unite_medicale"];
                        $unite_medicale_id = get_unite_medicale($BUF_record["unite_medicale"]);
                        $date_entree = sqlDate($BUF_record["date_entree"]);
                        $date_sortie = sqlDate($BUF_record["date_sortie"]);
                        $rss_id = get_rss($no_rss);
                        
                        foreach ($BUF_record["actes"] as $BUF_acte) {
                        
                            $BUF_code_acte = trim(substr($BUF_acte , 8, 7));
                            $BUF_date_acte = trim(substr($BUF_acte , 0, 8));
                            $BUF_extension_atih = (intval($BUF_record["version_format"]) >= 117 && trim(substr($BUF_acte , 15, 3) != '-00')) ? trim(substr($BUF_acte , 15, 3)) : "";
                            $BUF_code_acte .= $BUF_extension_atih;
                            $BUF_activite_ccam = trim(substr($BUF_acte , 16 + $BUF_record["offset_format"], 1));
                            if (! controle_check_num($BUF_activite_ccam,1, FALSE,$none,$none)) {
                                $BUF_activite_ccam = "1";
                            }
                            
                            
                            $deja = "";
                            $key = trim("$no_rss$BUF_code_acte$BUF_activite_ccam");
                            $deja = @$actesM_array[$key];
                            
                            $acte_id = get_acte($BUF_code_acte);

                            if ($deja != "O") {
                            
                                if ($rss_id > 0) {
                                
                                    $finess = $BUF_record["finess"];

                                    $date_acte = sqlDate($BUF_date_acte);
                                    if (!controle_check_date($BUF_date_acte,$none,$none)) {
                                        $date_acte = sqlDate($BUF_record["date_entree"]);
                                    }
                                    $phase_ccam = trim(substr($BUF_acte , 15 + $BUF_record["offset_format"], 1));
                                    $activite_ccam = trim(substr($BUF_acte , 16 + $BUF_record["offset_format"], 1));
                                    if (! controle_check_num($activite_ccam,1, FALSE,$none,$none)) {
                                        $activite_ccam = "1";
                                    }
                                    $extension_ccam = trim(substr($BUF_acte , 17 + $BUF_record["offset_format"], 1));
                                    $modificateur_ccam_1 = trim(substr($BUF_acte , 18 + $BUF_record["offset_format"], 1));
                                    $modificateur_ccam_2 = trim(substr($BUF_acte , 19 + $BUF_record["offset_format"], 1));
                                    $modificateur_ccam_3 = trim(substr($BUF_acte , 20 + $BUF_record["offset_format"], 1));
                                    $modificateur_ccam_4 = trim(substr($BUF_acte , 21 + $BUF_record["offset_format"], 1));
                                    $remboursement_excp_ccam = trim(substr($BUF_acte , 22 + $BUF_record["offset_format"], 1));
                                    $association_nonprevue_ccam = trim(substr($BUF_acte , 23 + $BUF_record["offset_format"], 1));
                                    $BUF_nombre = trim(substr($BUF_acte , 24 + $BUF_record["offset_format"], 8));
                                    $nombre = get_num($BUF_nombre,1);
                                    
                                    $medecin_id = 0;
                                    // Medecin acte
                                    $cle = get_numrss($BUF_record["no_rss"]) . $BUF_code_acte . get_date_AAAAMMJJ($BUF_date_acte) . $activite_ccam ;
                                    
                                    $code_med = "";
                                    $code_med = $actmed_array[$cle];
                                    if ($code_med == "") {
                                        $cle = get_numrss($BUF_record["no_rss"]) . $BUF_code_acte . "00000000" . $activite_ccam;
                                        $code_med = "";
                                        $code_med = $actmed_array[$cle];
                                    }
                                    if ($code_med != "") {
                                        $medecin_id = get_medecin($code_med);
                                    }
                                    
                                    
                                    
                                    $sqlcmd = "$sqlcmd_insert_acte VALUES( $rss_id,  '$finess',  $no_rss,  $no_rum,  '$unite_medicale', $unite_medicale_id, '$date_acte', $medecin_id, $acte_id, $acte_id, $nombre, '$phase_ccam', '$activite_ccam', '$extension_ccam', '$modificateur_ccam_1', '$modificateur_ccam_2', '$modificateur_ccam_3', '$modificateur_ccam_4', '$remboursement_excp_ccam', '$association_nonprevue_ccam') ";
                                    $sqlcmd_exec = "$sqlcmd_exec$sqlcmd;";
                                    $nbW_actes++;
                                    //$toResult = execute_sql($sqlcmd, $nbE, $nbW_actes );
                                    
                                }
                            }
                            
                            // Modification n° RUM
                            else {
                                $sqlcmd = "UPDATE temp.p_rss_actes SET no_rum = $no_rum, unite_medicale = '$unite_medicale', unite_medicale_id = $unite_medicale_id ";
                                $sqlcmd = $sqlcmd . "WHERE rss_id = $rss_id AND acte_id = $acte_id AND date_acte BETWEEN '$date_entree' AND '$date_sortie' AND no_rum = 0";
                                $sqlcmd_exec = "$sqlcmd_exec$sqlcmd;";
                                $toResult = execute_sql($sqlcmd, $nbE);
                            
                            }

                        }
                        
                    }
                }
            
            }
            
            fclose($handle);
        
        }
    
    
    }
    
    if ($sqlcmd_exec != "") {
        $toResult = execute_sql($sqlcmd_exec, $nbE, $nbW_actesxx );
        $sqlcmd_exec = "";
    }
    

    
    commit_trans();
    
    // Association rss mère au bébé
    
    // Première phase : les n° factures bébés sont désormais indiquées
    
    /* christophe */
    // RSS Id de la mère 
    logInfoMsg("Recherche des ID RSS de la mère pour les bébés");
    
    $sqlcmd = "DROP TABLE IF EXISTS w_mere;
        CREATE TEMP TABLE w_mere AS 
                SELECT 
                    p_rsf_total.no_rss AS no_rss_mere,
                    p_rsf_total.rss_id AS rss_mere_id,
                    p_rsf_total_bb.no_rss AS no_rss_bb,
                    p_rsf_total_bb.rss_id AS rss_bb_id,
                    lpad(p_rsf_total.no_facture, 9, '0') as no_facture
                FROM temp.p_rsf_total
                    JOIN temp.p_rss ON p_rsf_total.rss_id = p_rss.oid
                    JOIN pmsi.t_ghm ON p_rss.ghm_id = t_ghm.oid
                    JOIN temp.p_rsf_total p_rsf_total_bb ON lpad(p_rsf_total.no_facture, 9, '0') = lpad(p_rsf_total_bb.no_facture_sejour_mere, 9, '0')
                    JOIN temp.p_rss p_rss_bb ON p_rsf_total_bb.rss_id = p_rss_bb.oid
                    JOIN pmsi.t_ghm t_ghm_bb ON p_rss_bb.ghm_id = t_ghm_bb.oid AND t_ghm_bb.code LIKE '15%' 
                WHERE t_ghm.code LIKE '14%' AND p_rsf_total.no_facture <> '' AND p_rsf_total.no_facture <> '0' AND p_rsf_total.no_facture <> '000000000' AND
                    p_rss_bb.date_entree BETWEEN p_rss.date_entree AND p_rss.date_sortie;";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();
    
    //On associe le rss_id de la mère au bébé
    $sqlcmd = "UPDATE temp.p_rss 
                SET rss_mere_id = w_mere.rss_mere_id
                FROM w_mere
                WHERE p_rss.oid = w_mere.rss_bb_id AND
                    p_rss.rss_mere_id IS DISTINCT FROM w_mere.rss_mere_id;";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();
    
    // Seconde phase : pour les anciens séjours
    
    $sqlcmd = "DROP TABLE IF EXISTS rss_mere;
            CREATE temp table rss_mere AS
            SELECT
                p_rss.oid as rss_id, date_entree, date_sortie, matricule_assure, p_rsf_detail.ghs_id, import_id, MIN(p_rsf_detail.ctid) AS rsf_detail_id_1, MAX(p_rsf_detail.ctid) AS rsf_detail_id_2, 
                count(*) as nb_enfants, 0::bigint as rss_enfant_id_1, 0::bigint as rss_enfant_id_2, 0::bigint as rss_enfant_id_3
            FROM temp.p_rsf_detail, temp.p_rss, pmsi.t_ghs, temp.p_rsf_total
            WHERE p_rsf_detail.rss_id = p_rss.oid
                AND p_rsf_total.rss_id = p_rss.oid
                AND p_rss.ghm_id In (select oid from pmsi.t_ghm where code like '14%')
                AND p_rsf_detail.ghs_id = t_ghs.oid
                AND prestation_id IN (SELECT oid FROM pmsi.t_prestations WHERE code = 'GHS') 
                AND t_ghs.code BETWEEN 5800 AND 5940
                AND matricule_assure <> '' 
                AND est_ligne_rss = '1'
            GROUP BY 1,2,3,4,5,6;";
    $toResult = execute_sql($sqlcmd, $nbE);
    commit_trans();

    $sqlcmd = "DROP TABLE IF EXISTS rss_enfant;
            CREATE temp table rss_enfant AS
            SELECT p_rss.oid as rss_id, date_entree, date_sortie, matricule_assure, ghs_id, import_id
            FROM temp.p_rss, pmsi.t_ghs, temp.p_rsf_total
            WHERE p_rss.ghm_id In (select oid from pmsi.t_ghm where code like '15%')
                AND ghs_id = t_ghs.oid and p_rsf_total.rss_id = p_rss.oid
                AND p_rss.base_remboursement = 0;";
    $toResult = execute_sql($sqlcmd, $nbE);
    commit_trans();

    $sqlcmd = "UPDATE rss_mere
            SET rss_enfant_id_1 = rss_enfant.rss_id
            FROM rss_enfant
            WHERE rss_enfant.matricule_assure <> '' AND
                rss_enfant.matricule_assure = rss_mere.matricule_assure AND
                rss_enfant.date_entree BETWEEN rss_mere.date_entree AND rss_mere.date_sortie AND
                rss_mere.ghs_id = rss_enfant.ghs_id AND 
                rss_mere.import_id = rss_enfant.import_id;";
    $toResult = execute_sql($sqlcmd, $nbE);
    commit_trans();

    $sqlcmd = "UPDATE rss_mere
            SET rss_enfant_id_2 = rss_enfant.rss_id
            FROM rss_enfant
            WHERE rss_enfant.matricule_assure <> '' AND
                rss_enfant.matricule_assure = rss_mere.matricule_assure AND 
                rss_enfant.date_entree BETWEEN rss_mere.date_entree AND rss_mere.date_sortie AND
                rss_mere.ghs_id = rss_enfant.ghs_id AND 
                rss_mere.import_id = rss_enfant.import_id AND
                rss_enfant.rss_id <> rss_enfant_id_1;";
    $toResult = execute_sql($sqlcmd, $nbE);
    commit_trans();

    $sqlcmd = "UPDATE rss_mere
            SET rss_enfant_id_3 = rss_enfant.rss_id
            FROM rss_enfant
            WHERE rss_enfant.matricule_assure <> '' AND
                rss_enfant.matricule_assure = rss_mere.matricule_assure AND
                rss_enfant.date_entree BETWEEN rss_mere.date_entree AND rss_mere.date_sortie AND
                rss_mere.ghs_id = rss_enfant.ghs_id AND
                rss_mere.import_id = rss_enfant.import_id AND
                rss_enfant.rss_id <> rss_enfant_id_1 AND
                rss_enfant.rss_id <> rss_enfant_id_2;";
    $toResult = execute_sql($sqlcmd, $nbE);
    commit_trans();

    $sqlcmd = "UPDATE temp.p_rss 
            SET rss_mere_id = rss_mere.rss_id
            FROM rss_mere
            WHERE p_rss.oid = rss_enfant_id_1 AND
                p_rss.rss_mere_id = 0;";
    $toResult = execute_sql($sqlcmd, $nbE);
    commit_trans();

    $sqlcmd = "UPDATE temp.p_rss 
            SET rss_mere_id = rss_mere.rss_id
            FROM rss_mere
            WHERE p_rss.oid = rss_enfant_id_2 AND
                p_rss.rss_mere_id = 0;";
    $toResult = execute_sql($sqlcmd, $nbE);
    commit_trans();

    $sqlcmd = "UPDATE temp.p_rss 
            SET rss_mere_id = rss_mere.rss_id
            FROM rss_mere
            WHERE p_rss.oid = rss_enfant_id_3 AND
                p_rss.rss_mere_id = 0;";
    $toResult = execute_sql($sqlcmd, $nbE);
    commit_trans();
    
    // Sur privé, réaffectation des GHS bébés
    if ($ENV_TYPEETS == "1" && $ENV_OPTPMSI_GHSBB == "1") {
        
        $sqlcmd = "WITH w_bb AS (
            SELECT oid as rss_bb_id, rss_mere_id, no_rss AS no_rss_bb
            FROM temp.p_rss
            WHERE rss_mere_id <> 0
            ), w_ids AS (
            SELECT p_rsf_detail.CTID AS ctid_detail_mere, w_bb.rss_mere_id, rss_bb_id, no_rss_bb
            FROM 
                temp.p_rsf_detail
                JOIN w_bb ON rss_mere_id = p_rsf_detail.rss_id
                JOIN temp.p_rss ON w_bb.rss_mere_id = p_rss.oid
                JOIN pmsi.t_ghs ON p_rsf_detail.ghs_id = t_ghs.oid
                JOIN pmsi.t_ghm ON t_ghs.ghm_id = t_ghm.oid
                WHERE t_ghm.code LIKE '15%'	
                AND p_rsf_detail.est_ligne_rss = '1'
            )
            UPDATE temp.p_rsf_detail
            SET rss_id = w_ids.rss_bb_id,
            no_rss = w_ids.no_rss_bb
            FROM w_ids
            WHERE p_rsf_detail.CTID = ctid_detail_mere
            AND p_rsf_detail.rss_id IS DISTINCT FROM w_ids.rss_bb_id
            ;";
        $toResult = execute_sql($sqlcmd, $nbE);
        commit_trans();
        
    }
    
// Sur public, ajustement des dates entree sortie / date prestation
    if ($ENV_TYPEETS != "1") {
        $sqlcmd = "UPDATE temp.p_rss
            SET date_sortie = date_fin
            FROM    
            (SELECT p_rsf_detail.rss_id, 
                date_entree, 
                date_sortie, 
                MAX(date_fin) AS date_fin
            FROM temp.p_rsf_detail
            JOIN temp.p_rss on p_rsf_detail.rss_id = p_rss.oid
            WHERE date_fin > date_sortie AND
                ghm_id = 0
            GROUP BY 1,2,3
            ) subview
            WHERE p_rss.oid = subview.rss_id";
            $toResult = execute_sql($sqlcmd, $nbE);
            commit_trans();
            
            $sqlcmd = "UPDATE temp.p_rss
            SET date_sortie = date_fin
            FROM    
            (SELECT p_rsf_detail.rss_id, 
                date_entree, 
                date_sortie, 
                MAX(date_fin) AS date_fin
            FROM temp.p_rsf_detail
            JOIN temp.p_rss on p_rsf_detail.rss_id = p_rss.oid
            JOIN pmsi.t_prestations ON t_prestations.oid = p_rsf_detail.prestation_id
            WHERE  date_sortie > date_fin   AND
                ghm_id = 0 AND t_prestations.code = 'ATU'
            GROUP BY 1,2,3
            ) subview
            WHERE p_rss.oid = subview.rss_id";
            $toResult = execute_sql($sqlcmd, $nbE);
            commit_trans();            
    }
    
    
// Sur public, traitement spécial activité libérale
// Le sejour est quand même pris en charge pour les types B (SEx, ATU, FFM)
// Les la facturation honoraire est supprimée 
    if ($ENV_TYPEETS != "1") {
        // La requête  DELETE FROM temp.p_rsf_detail a été déplacée dans le bloc des prestations non valorisées (règle 15)
        $sqlcmd = "
            UPDATE temp.p_rsf_total
            SET code_pec = '1', code_pec_id = t_pec.oid
            FROM base.t_motif_non_facturation, base.t_pec
            WHERE code_pec = '0' AND
                t_pec.code = '1' AND
                motif_non_facturation_id = t_motif_non_facturation.oid AND
                t_motif_non_facturation.code = '6';";
            $toResult = execute_sql($sqlcmd, $nbE);
            commit_trans();
    }
    
    
// Sur public, ajustement base de remboursement ATU à 0
    if ($ENV_TYPEETS != "1") {
        $sqlcmd = "UPDATE temp.p_rsf_detail SET 
                base_remboursement = round(nombre * coefficient * coefficient_mco * prix_unitaire,2),
                base_remboursement_sauf_transition = round(nombre * coefficient * coefficient_geo * prix_unitaire,2),
                taux_remboursement = 100,
                update_rules = array_append(update_rules, 1)
            FROM temp.p_rss 
            WHERE rss_id = p_rss.oid AND
                p_rsf_detail.base_remboursement = 0 AND
                prestation_id IN (SELECT oid FROM pmsi.t_prestations WHERE code = 'ATU')";
            $toResult = execute_sql($sqlcmd, $nbE);
            commit_trans();
    }
    
// Sur public, replication coefficient MCO sur SEx, ATU
    if ($ENV_TYPEETS != "1") {
        // Remise à 1 du coefficient MCO sur les lignes 'C'
        $sqlcmd = "UPDATE temp.p_rsf_detail 
            SET coefficient_mco = 1,
                update_rules = array_append(update_rules, 3)
            FROM pmsi.t_prestations
            WHERE p_rsf_detail.prestation_id = t_prestations.oid 
            AND p_rsf_detail.est_ligne_rss = '1' 
            AND type = 'C'
            AND t_prestations.code NOT IN ('ATU', 'SE1', 'SE2', 'SE3', 'SE4', 'SE5', 'SE6', 'SE7', 'APE', 'FFM', 'AP2', 'FPI')
            AND coefficient_mco IS DISTINCT FROM 1
            ";
        $toResult = execute_sql($sqlcmd, $nbE);
        commit_trans();
        
        // CLA le 14-11-2017
        // Remise à 1 du coefficient MCO sur les lignes 'B' si à 0
        $sqlcmd = " UPDATE temp.p_rsf_detail SET 
                        coefficient_mco = 1,
                        update_rules = array_append(update_rules, 4)
                    FROM pmsi.t_prestations
                    WHERE 1=1
                        AND p_rsf_detail.prestation_id = t_prestations.oid 
                        AND p_rsf_detail.est_ligne_rss = '1' 
                        AND type = 'B'
                        AND t_prestations.code IN ('ATU', 'SE1', 'SE2', 'SE3', 'SE4', 'SE5', 'SE6', 'SE7', 'APE', 'FFM', 'AP2', 'FPI')
                        AND coefficient_mco = 0
                    ";
        $toResult = execute_sql($sqlcmd, $nbE);
        commit_trans();
            
        // Si nombre de SE = 0 alors mettre nombre à 1
        $sqlcmd = "UPDATE temp.p_rsf_detail 
                SET nombre = 1,
                    update_rules = array_append(update_rules, 5)
                FROM pmsi.t_prestations
                WHERE p_rsf_detail.prestation_id = t_prestations.oid AND
                    t_prestations.code IN ('ATU', 'FTN', 'FTR', 'SE1', 'SE2', 'SE3', 'SE4', 'SE5', 'SE6', 'SE7', 'APE', 'FFM') AND
                    nombre = 0;";
            $toResult = execute_sql($sqlcmd, $nbE);
            commit_trans();
            
        // Si taux remboursement PII externes à 0, mettre 100
        $sqlcmd = "UPDATE temp.p_rsf_detail 
                SET taux_remboursement = 100,
                    sejour_remboursable = base_remboursement,
                    update_rules = array_append(update_rules, 6)
                FROM pmsi.t_prestations
                WHERE p_rsf_detail.prestation_id = t_prestations.oid AND
                    t_prestations.code IN ('PII') AND
                    taux_remboursement = 0;";
            $toResult = execute_sql($sqlcmd, $nbE);
            commit_trans();
            
        
        // valorisation 
        // Modif CLA 16-07-2018 semble ne plus s'appliquer aux Forfaits techniques (FTN, FTG, FTR) dont base_remboursement = pu * qte * nb * coef_transition
        $sqlcmd = "UPDATE temp.p_rsf_detail 
                SET base_remboursement = round(round(nombre * prix_unitaire * coefficient_mco,2) * coefficient, 2),
                    base_remboursement_sauf_transition = round(round(nombre * prix_unitaire * coefficient_geo, 2) * coefficient, 2),
                    update_rules = array_append(update_rules, 7)
                FROM 
                pmsi.t_prestations, temp.p_rss 
                WHERE p_rsf_detail.prestation_id = t_prestations.oid 
                AND p_rss.import_id = $import_id
                AND p_rsf_detail.rss_id = p_rss.oid AND p_rsf_detail.est_ligne_rss = '1'
                AND t_prestations.code IN ('ATU', 'SE1', 'SE2', 'SE3', 'SE4', 'SE5', 'SE6', 'SE7', 'APE', 'FFM', 'AP2', 'FPI')
                AND 
                    (
                        p_rsf_detail.base_remboursement IS DISTINCT FROM round(round(nombre * prix_unitaire * coefficient_mco,2) * coefficient, 2) OR
                        p_rsf_detail.base_remboursement_sauf_transition IS DISTINCT FROM round(round(nombre * prix_unitaire * coefficient_geo, 2) * coefficient, 2)
                    
                    );";
            $toResult = execute_sql($sqlcmd, $nbE);
            commit_trans();
        
        // forfaits techniques : base_remboursement = pu * qte * nb * coef_transition
        $sqlcmd = "UPDATE temp.p_rsf_detail 
                SET base_remboursement = round(nombre * prix_unitaire * coefficient,2),
                    base_remboursement_sauf_transition = round(nombre * prix_unitaire * coefficient,2),
                    update_rules = array_append(update_rules, 8)
                FROM 
                    pmsi.t_prestations, temp.p_rss 
                WHERE 
                    p_rsf_detail.prestation_id = t_prestations.oid 
                    AND p_rss.import_id = $import_id
                    AND p_rsf_detail.rss_id = p_rss.oid AND p_rsf_detail.est_ligne_rss = '1'
                    AND t_prestations.code IN ('FTR', 'FTN', 'FTG', 'FTS', 'FR2', 'FR3')
                    AND 
                        (
                            p_rsf_detail.base_remboursement IS DISTINCT FROM round(nombre * prix_unitaire * coefficient,2) OR
                            p_rsf_detail.base_remboursement_sauf_transition IS DISTINCT FROM round(nombre * prix_unitaire * coefficient,2)
                        );";
            $toResult = execute_sql($sqlcmd, $nbE);
            commit_trans();
            
        // Recalcul prix unitaire sur CCAM 
        $sqlcmd = "UPDATE temp.p_rsf_detail 
                SET prix_unitaire = round(p_rsf_detail.base_remboursement / p_rsf_detail.nombre / p_rsf_detail.coefficient / p_rsf_detail.coefficient_mco,2),
                    sejour_remboursable = round(p_rsf_detail.base_remboursement * p_rsf_detail.taux_remboursement / 100.00,2),
                    update_rules = array_append(update_rules, 9)
                FROM 
                pmsi.t_prestations,temp.p_rss 
                WHERE p_rsf_detail.prestation_id = t_prestations.oid 
                AND p_rsf_detail.rss_id = p_rss.oid AND p_rsf_detail.type = 'C' AND p_rsf_detail.est_ligne_rss = '1' 
                AND t_prestations.code IN ('ADC', 'ADA', 'ATM', 'ACO', 'ADE', 'ADI', 'DEN')
                AND p_rss.import_id = $import_id
                AND p_rsf_detail.coefficient_mco = 1
                AND p_rsf_detail.nombre <> 0 
                AND p_rsf_detail.coefficient <> 0 
                AND p_rsf_detail.base_remboursement <> 0 
                AND (
                    prix_unitaire <> round(p_rsf_detail.base_remboursement / p_rsf_detail.nombre / p_rsf_detail.coefficient / p_rsf_detail.coefficient_mco,2) OR
                    sejour_remboursable IS DISTINCT FROM round(p_rsf_detail.base_remboursement * p_rsf_detail.taux_remboursement / 100.00,2)
                    );";
            $toResult = execute_sql($sqlcmd, $nbE);
            commit_trans();
        
        // Coeff MCO
        $sqlcmd = "UPDATE temp.p_rsf_detail 
                SET 
                    nombre = CASE WHEN nombre > 0 THEN 0 - nombre ELSE nombre END,
                    taux_remboursement = 100,
                    base_remboursement = CASE WHEN p_rsf_detail.base_remboursement > 0 THEN 0 - p_rsf_detail.base_remboursement ELSE p_rsf_detail.base_remboursement END,
                    sejour_facture = CASE WHEN p_rsf_detail.sejour_facture > 0 THEN 0 - p_rsf_detail.sejour_facture ELSE p_rsf_detail.sejour_facture END,
                    sejour_remboursable = CASE WHEN p_rsf_detail.base_remboursement > 0 THEN 0 - p_rsf_detail.base_remboursement ELSE p_rsf_detail.base_remboursement END,
                    update_rules = array_append(update_rules, 11)
                FROM 
                    pmsi.t_prestations, temp.p_rss
                WHERE p_rsf_detail.prestation_id = t_prestations.oid 
                AND p_rss.import_id = $import_id
                AND p_rsf_detail.rss_id = p_rss.oid AND p_rsf_detail.type = 'C' AND p_rsf_detail.est_ligne_rss = '1' 
                AND t_prestations.code IN ('PAE', 'PAT')
                AND (
                    p_rsf_detail.nombre <> CASE WHEN nombre > 0 THEN 0 - nombre ELSE nombre END OR
                    p_rsf_detail.taux_remboursement <> 100 OR
                    p_rsf_detail.base_remboursement <> CASE WHEN p_rsf_detail.base_remboursement > 0 THEN 0 - p_rsf_detail.base_remboursement ELSE p_rsf_detail.base_remboursement END OR
                    p_rsf_detail.sejour_facture <> CASE WHEN p_rsf_detail.sejour_facture > 0 THEN 0 - p_rsf_detail.sejour_facture ELSE p_rsf_detail.sejour_facture END OR
                    p_rsf_detail.sejour_remboursable <> CASE WHEN p_rsf_detail.base_remboursement > 0 THEN 0 - p_rsf_detail.base_remboursement ELSE p_rsf_detail.base_remboursement END
                )";
        $toResult = execute_sql($sqlcmd, $nbE);
        commit_trans();
        
        
        // Recalcul base de remboursement sur NGAP 
        $sqlcmd = "UPDATE temp.p_rsf_detail 
                SET base_remboursement = round(nombre * coefficient * prix_unitaire * coefficient_mco,2),
                    base_remboursement_sauf_transition = round(nombre * coefficient * prix_unitaire * coefficient_mco,2),
                    sejour_facture = round(nombre * coefficient * prix_unitaire * coefficient_mco,2),
                    update_rules = array_append(update_rules, 12)
                FROM 
                pmsi.t_prestations,temp.p_rss 
                WHERE p_rsf_detail.prestation_id = t_prestations.oid 
                AND p_rsf_detail.rss_id = p_rss.oid AND p_rsf_detail.type = 'C' AND p_rsf_detail.est_ligne_rss = '1' 
                AND t_prestations.code NOT IN ('ADC', 'ADA', 'ATM', 'ACO', 'ADE', 'ADI', 'DEN')
                AND t_prestations.code NOT LIKE '% N'
                AND t_prestations.code NOT LIKE '% F'
                AND p_rss.import_id = $import_id
                AND p_rsf_detail.nombre <> 0 
                AND p_rsf_detail.prix_unitaire <> 0 
                AND p_rsf_detail.coefficient <> 0 
                AND p_rsf_detail.type = 'C'
                AND (
                    p_rsf_detail.base_remboursement IS DISTINCT FROM round(nombre * prix_unitaire * coefficient_mco * coefficient,2)
                    );";
            $toResult = execute_sql($sqlcmd, $nbE);
            commit_trans();
            
        $sqlcmd = "UPDATE temp.p_rsf_detail 
                SET montant_supplement_nf = p_rsf_detail.base_remboursement - round(nombre * coefficient * prix_unitaire,2) ,
                    update_rules = array_append(update_rules, 13)
                FROM 
                    pmsi.t_prestations, temp.p_rss
                WHERE p_rsf_detail.prestation_id = t_prestations.oid 
                AND p_rss.import_id = $import_id
                AND p_rsf_detail.rss_id = p_rss.oid AND p_rsf_detail.type = 'C' AND p_rsf_detail.est_ligne_rss = '1' 
                AND (t_prestations.code LIKE '% N' OR t_prestations.code LIKE '% F')
                AND montant_supplement_nf IS DISTINCT FROM p_rsf_detail.sejour_facture - round(nombre * coefficient * prix_unitaire,2)";
        $toResult = execute_sql($sqlcmd, $nbE);
        commit_trans();
        
        // Arrondis NGAP base_remboursement, sur plus gros dossier (sauf VALOACE)
		if (! $file_exists_VSE) {
			$sqlcmd = "DROP TABLE IF EXISTS w_ecarts_mco;
					CREATE TEMP TABLE w_ecarts_mco AS
					SELECT code_pec_id, 
						prestation_id AS ecart_prestation_id, 
						prix_unitaire AS ecart_prix_unitaire, 
						(MAX(array[p_rsf_detail.base_remboursement_sauf_transition , p_rsf_detail.rss_id]))[2] AS ecart_rss_id,
						null::tid AS ecart_ctid,
						SUM(p_rsf_detail.base_remboursement) - round(SUM(nombre*coefficient*coefficient_mco) * prix_unitaire,2) AS ecart_montant
					FROM temp.p_rss
						JOIN temp.p_rsf_detail ON p_rsf_detail.rss_id = p_rss.oid
						JOIN temp.p_rsf_total ON p_rsf_total.rss_id = p_rss.oid
						JOIN pmsi.t_prestations ON prestation_id = t_prestations.oid
					WHERE p_rsf_detail.type = 'C' AND 
						p_rsf_detail.est_ligne_rss = '1' AND
						t_prestations.code NOT IN ('ADC', 'ADA', 'ATM', 'ACO', 'ADE', 'ADI', 'DEN') AND
						t_prestations.code NOT LIKE '% N' AND
						t_prestations.code NOT LIKE '% F' AND
						p_rsf_detail.nombre <> 0 AND
						p_rsf_detail.prix_unitaire <> 0 AND
						p_rsf_detail.coefficient <> 0 
					GROUP BY 1,2,3
					HAVING round(SUM(nombre*coefficient*coefficient_mco) * prix_unitaire,2) <> SUM(p_rsf_detail.base_remboursement);";
			$toResult = execute_sql($sqlcmd, $nbE);
			commit_trans();



			$sqlcmd = "UPDATE w_ecarts_mco
					SET ecart_ctid = p_rsf_detail.CTID
					FROM temp.p_rsf_detail
					WHERE p_rsf_detail.rss_id = ecart_rss_id AND
						p_rsf_detail.prestation_id = ecart_prestation_id AND 
						p_rsf_detail.prix_unitaire = ecart_prix_unitaire AND 
						ecart_montant <> 0 AND
						est_ligne_rss = '1' ;";
			$toResult = execute_sql($sqlcmd, $nbE);
			commit_trans();


			$sqlcmd = "UPDATE temp.p_rsf_detail SET
						base_remboursement = base_remboursement - ecart_montant,
						base_remboursement_sauf_transition = base_remboursement - ecart_montant,
						update_rules = array_append(update_rules, 14)
					FROM w_ecarts_mco
					WHERE p_rsf_detail.CTID = ecart_ctid AND 
						ecart_montant <> 0;";
			$toResult = execute_sql($sqlcmd, $nbE);
			commit_trans();
		}

        // Taux remboursement sur PAP
        
        $sqlcmd = "UPDATE temp.p_rsf_detail 
                SET taux_remboursement = CASE WHEN p_rsf_detail.taux_remboursement = 0 AND t_prestations.code = 'PAP' AND t_pec.code <> '0' THEN 100 
                                        WHEN p_rsf_detail.taux_remboursement > 0 THEN p_rsf_detail.taux_remboursement 
                                        WHEN t_pec.code <> '0' THEN 70 ELSE 0 END,
                    update_rules = array_append(update_rules, 15)
                FROM 
                pmsi.t_prestations, temp.p_rss, temp.p_rsf_total, base.t_pec
                WHERE p_rsf_detail.prestation_id = t_prestations.oid 
                AND t_pec.oid = p_rsf_total.code_pec_id
                AND p_rss.import_id = $import_id
                AND p_rsf_detail.rss_id = p_rss.oid AND p_rsf_total.rss_id = p_rss.oid AND p_rsf_detail.type = 'C' AND p_rsf_detail.est_ligne_rss = '1' 
                AND 
                    (
                    p_rsf_detail.base_remboursement <> round(((nombre * prix_unitaire * coefficient) + COALESCE(montant_supplement_nf,0)) * coefficient_mco ,2) OR
                    p_rsf_detail.taux_remboursement <> 
                                    CASE WHEN p_rsf_detail.taux_remboursement = 0 AND t_prestations.code = 'PAP' AND t_pec.code <> '0' THEN 100 
                                        WHEN p_rsf_detail.taux_remboursement > 0 THEN p_rsf_detail.taux_remboursement 
                                        WHEN t_pec.code <> '0' THEN 70 ELSE 0 END
                    )
                ";
        $toResult = execute_sql($sqlcmd, $nbE);
        commit_trans();
            
        $sqlcmd = "UPDATE temp.p_rsf_detail 
                SET sejour_remboursable = round(p_rsf_detail.base_remboursement * p_rsf_detail.taux_remboursement / 100,2),
                    update_rules = array_append(update_rules, 16)
                FROM 
                pmsi.t_prestations, temp.p_rss, temp.p_rsf_total
                WHERE p_rsf_detail.prestation_id = t_prestations.oid 
                AND p_rss.import_id = $import_id
                AND p_rsf_detail.rss_id = p_rss.oid AND p_rsf_total.rss_id = p_rss.oid AND p_rsf_detail.type = 'C' AND p_rsf_detail.est_ligne_rss = '1' 
                AND p_rsf_detail.sejour_remboursable <> round(p_rsf_detail.base_remboursement * p_rsf_detail.taux_remboursement / 100,2)
                AND p_rsf_detail.sejour_remboursable IS DISTINCT FROM round(p_rsf_detail.base_remboursement * p_rsf_detail.taux_remboursement / 100,2)
                ";
            $toResult = execute_sql($sqlcmd, $nbE);
            commit_trans(); 

        // Taux remboursement = 94% Sur SEh, ATU
        // jusqu'au 07 octobre 2015
        $sqlcmd = "UPDATE temp.p_rsf_detail 
                SET taux_remboursement = CASE WHEN t_pec.code <> '0' THEN 94 ELSE 0 END,
                    update_rules = array_append(update_rules, 17)
                FROM 
                pmsi.t_prestations, temp.p_rss, temp.p_rsf_total, base.t_pec
                WHERE p_rsf_detail.prestation_id = t_prestations.oid 
                AND t_pec.oid = p_rsf_total.code_pec_id
                AND p_rss.import_id = $import_id
                AND ghm_id = 0
                AND p_rsf_detail.rss_id = p_rss.oid AND p_rsf_total.rss_id = p_rss.oid AND p_rsf_detail.est_ligne_rss = '1' 
                AND prestation_id IN (SELECT oid FROM pmsi.t_prestations WHERE code IN ('ATU', 'SE1', 'SE2', 'SE3', 'SE4', 'SE5', 'SE6', 'SE7', 'APE', 'FFM', 'AP2', 'FPI'))
                AND p_rsf_detail.taux_remboursement <> CASE WHEN t_pec.code <> '0' THEN 94 ELSE 0 END
                AND p_rsf_detail.date_debut < '20151007'::date";
        $toResult = execute_sql($sqlcmd, $nbE);
        commit_trans();

        // Forçage du Tx de remboursement si différent des valeurs autorisées (80,90,100) à aprtir du 07 octobre 2015
        // Guide de lecture OVALIDE exDGF 2016 page 84
        $sqlcmd = " UPDATE temp.p_rsf_detail SET
                        taux_remboursement = 80,
                    update_rules = array_append(update_rules, 18)
                    FROM
                        pmsi.t_prestations
                    WHERE 1=1
                        AND t_prestations.oid = p_rsf_detail.prestation_id
                        AND p_rsf_detail.date_debut >= '20151007'::date
                        AND t_prestations.code IN ('SE1', 'SE2', 'SE3', 'SE4', 'SE5', 'SE6', 'SE7', 'FFM', 'APE', 'ATU')
                        AND p_rsf_detail.taux_remboursement NOT IN (80, 90, 100);";
        $toResult = execute_sql($sqlcmd, $nbE);
        commit_trans();
        
        // Même chose mais pour les ATM associés à ces forfaits
        $sqlcmd = " UPDATE temp.p_rsf_detail SET
                        taux_remboursement = 80,
                        update_rules = array_append(update_rules, 19)
                    FROM
                        pmsi.t_prestations
                    WHERE 1=1
                        AND t_prestations.oid = p_rsf_detail.prestation_id
                        AND t_prestations.code = 'ATM'
                        AND taux_remboursement NOT IN (80, 90, 100)
                        AND p_rsf_detail.rss_id = ANY(ARRAY(    SELECT rss_id 
                                                                FROM temp.p_rsf_detail 
                                                                JOIN pmsi.t_prestations ON t_prestations.oid = p_rsf_detail.prestation_id
                                                                WHERE 1=1
                                                                    AND t_prestations.code IN ('SE1', 'SE2', 'SE3', 'SE4', 'SE5', 'SE6', 'SE7', 'FFM', 'APE', 'ATU', 'AP2', 'FPI')
                                                                    AND p_rsf_detail.date_debut >= '20151007'::date
                                                                GROUP BY 1
                                                            )::bigint[]);";
        $toResult = execute_sql($sqlcmd, $nbE);
        commit_trans();
        
        // Si Taux = 0 sur FTN, FTR alors 60
        // Modif CLA du 10-11-2015. Le taux de remboursement semble être passé à 70% depuis 2015
        $sqlcmd = "UPDATE temp.p_rsf_detail 
                SET taux_remboursement = 
                    --CASE WHEN date_debut >= '20150301'::date THEN 70 ELSE 60 END
                    60,
                    update_rules = array_append(update_rules, 20)
                FROM pmsi.t_prestations
                WHERE p_rsf_detail.prestation_id = t_prestations.oid AND
                    t_prestations.code IN ('FTN', 'FTR') AND
                    taux_remboursement <> 100;";
            $toResult = execute_sql($sqlcmd, $nbE);
            commit_trans();

        // recalcul sejour remboursable SUR ATU, SEh, FTN, FTR
        $sqlcmd = "UPDATE temp.p_rsf_detail 
                SET sejour_remboursable = round(p_rsf_detail.base_remboursement * p_rsf_detail.taux_remboursement / 100,2),
                sejour_remboursable_2 = p_rsf_detail.base_remboursement - round(p_rsf_detail.base_remboursement * p_rsf_detail.taux_remboursement / 100,2),
                update_rules = array_append(update_rules, 21)
                FROM 
                pmsi.t_prestations, temp.p_rss, temp.p_rsf_total
                WHERE p_rsf_detail.prestation_id = t_prestations.oid 
                AND p_rss.import_id = $import_id
                AND ghm_id = 0
                AND p_rsf_detail.rss_id = p_rss.oid AND p_rsf_total.rss_id = p_rss.oid AND p_rsf_detail.est_ligne_rss = '1' 
                AND prestation_id IN (SELECT oid FROM pmsi.t_prestations WHERE code IN ('ATU', 'SE1', 'SE2', 'SE3', 'SE4', 'SE5', 'SE6', 'SE7', 'FTN', 'FTR', 'APE', 'FFM', 'AP2', 'FPI'))
                AND (
                    p_rsf_detail.sejour_remboursable <> round(p_rsf_detail.base_remboursement * p_rsf_detail.taux_remboursement / 100,2) OR
                    p_rsf_detail.sejour_remboursable_2 <> p_rsf_detail.base_remboursement - round(p_rsf_detail.base_remboursement * p_rsf_detail.taux_remboursement / 100,2)
                    );";
        $toResult = execute_sql($sqlcmd, $nbE);
        commit_trans();    
        
        /*
        // Sur les forfaits techniques qui sont comptabilités en prestations cliniques (erreur décelée à Baclesse mais peut apparaitre ailleurs)
        // Recalcul du montant remboursé s'il est supérieurs à la base de remboursement
        // La dernière condition permet de s'afranchir des erreurs d'arrondi            
        $sqlcmd = "UPDATE temp.p_rsf_detail 
                SET sejour_remboursable = round(p_rsf_detail.base_remboursement * p_rsf_detail.taux_remboursement / 100, 2)
                FROM 
                    pmsi.v_listes_contenu_1
                WHERE 1=1
                    AND p_rsf_detail.type = 'B'
                    AND v_listes_contenu_1.liste_code = 'CTI_FT_P'
                    AND p_rsf_detail.prestation_id = v_listes_contenu_1.to_id
                    AND round(p_rsf_detail.sejour_remboursable) > round(p_rsf_detail.base_remboursement) + 1;
                ";
        $toResult = execute_sql($sqlcmd, $nbE);
        commit_trans(); 
        */

    }
    
// Sur public, Lettres clés non valorisées
    if ($ENV_TYPEETS != "1") {
    
    
        logInfoMsg("Lettres clés non valorisées");
        
        $sqlcmd = "DROP TABLE IF EXISTS w_non_valorises;
                CREATE TEMP TABLE w_non_valorises (fromctid tid, rss_id bigint, regle_id bigint)";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
        commit_trans();
        
        // 16 : Lettre clé hors période
        $sqlcmd = "INSERT INTO w_non_valorises
            SELECT 
                p_rsf_detail.CTID AS fromCTID, p_rsf_detail.rss_id, COALESCE(t_regles_non_valorisation.oid, 0) as regle_id
            FROM 
                temp.p_rsf_detail
                LEFT JOIN pmsi.t_regles_non_valorisation ON t_regles_non_valorisation.code = '16'::text
                WHERE 1=1
                    AND p_rsf_detail.date_fin >= to_date($annee_mois_fin, 'YYYYMM') + interval '1 month'
                    AND p_rsf_detail.type = 'C';";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
        commit_trans();
        
        // Les avis ponctuels de consultants ne sont valorisés qu'à partir du 01 octobre 2017
        $sqlcmd = "INSERT INTO w_non_valorises
            SELECT 
                p_rsf_detail.CTID AS fromCTID, p_rsf_detail.rss_id, COALESCE(t_regles_non_valorisation.oid, 0) as regle_id
            FROM 
                temp.p_rsf_detail
                JOIN pmsi.t_prestations ON prestation_id = t_prestations.oid
                LEFT JOIN pmsi.t_regles_non_valorisation ON t_regles_non_valorisation.code = '16'::text
                WHERE 1=1
                    AND t_prestations.code IN ('APC','APV','APY','AVY','APU')
                    AND p_rsf_detail.date_fin < '20171001'::date;";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
        commit_trans();
        
        // MCS incompatible avec ATU
        $sqlcmd = "INSERT INTO w_non_valorises
                SELECT p_rsf_detail.CTID AS fromCTID, p_rsf_detail.rss_id, COALESCE(t_regles_non_valorisation.oid, 0) as regle_id
                FROM temp.p_rsf_detail
                JOIN pmsi.t_prestations ON prestation_id = t_prestations.oid
                LEFT JOIN pmsi.t_regles_non_valorisation ON t_regles_non_valorisation.code = '01'::text
                WHERE t_prestations.code = 'MCS' AND
                    date_debut >= '20130301' AND
                    rss_id IN (
                        SELECT rss_id
                        FROM temp.p_rsf_detail
                        JOIN pmsi.t_prestations ON prestation_id = t_prestations.oid
                        WHERE t_prestations.code IN ('ATU', 'MCS') AND est_ligne_rss = '1' AND date_debut >= '20130301'
                        GROUP BY 1
                        HAVING count(*) > 1 AND
                            MIN(prestation_id) <> MAX(prestation_id)
                        );";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
        commit_trans();
        
        // MCG incompatible avec ATU
        $sqlcmd = "INSERT INTO w_non_valorises
                SELECT p_rsf_detail.CTID AS fromCTID, p_rsf_detail.rss_id, COALESCE(t_regles_non_valorisation.oid, 0) as regle_id
                FROM temp.p_rsf_detail
                JOIN pmsi.t_prestations ON prestation_id = t_prestations.oid
                LEFT JOIN pmsi.t_regles_non_valorisation ON t_regles_non_valorisation.code = '02'::text
                WHERE t_prestations.code = 'MCG' AND
                    date_debut >= '20130101' AND
                    rss_id IN (
                        SELECT rss_id
                        FROM temp.p_rsf_detail
                        JOIN pmsi.t_prestations ON prestation_id = t_prestations.oid
                        WHERE t_prestations.code IN ('ATU', 'MCG') AND est_ligne_rss = '1' AND date_debut >= '20130101'
                        GROUP BY 1
                        HAVING count(*) > 1 AND
                            MIN(prestation_id) <> MAX(prestation_id)
                        );";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
        commit_trans();
        
        // FSD en double
        
        $sqlcmd = "INSERT INTO w_non_valorises
                SELECT p_rsf_detail.CTID AS fromCTID, p_rsf_detail.rss_id, COALESCE(t_regles_non_valorisation.oid, 0) as regle_id
                FROM temp.p_rsf_detail
                JOIN pmsi.t_prestations ON prestation_id = t_prestations.oid
                LEFT JOIN pmsi.t_regles_non_valorisation ON t_regles_non_valorisation.code = '03'::text
                WHERE t_prestations.code = 'FSD' AND
                    date_debut >= '20130101' AND
                    rss_id IN (
                        SELECT rss_id
                        FROM temp.p_rsf_detail
                        JOIN pmsi.t_prestations ON prestation_id = t_prestations.oid
                        WHERE t_prestations.code IN ('FSD') AND est_ligne_rss = '1' AND
                            date_debut >= '20130101'
                            group by 1
                            having count(*) > 1
                        );";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
        commit_trans();
        
        // Mauvais prix unitaire 2.Q.MNTPU
        // CLA 2019-03-08 Il ne faut pas exclure les erreurs de prix unitaire sur les CMU
        $sqlcmd = "INSERT INTO w_non_valorises
                SELECT p_rsf_detail.CTID AS fromCTID, p_rsf_detail.rss_id, COALESCE(t_regles_non_valorisation.oid, 0) as regle_id
                FROM temp.p_rsf_detail
                JOIN temp.p_rsf_total ON p_rsf_total.rss_id = p_rsf_detail.rss_id
                JOIN pmsi.t_prestations ON prestation_id = t_prestations.oid
                LEFT JOIN pmsi.t_regles_non_valorisation ON t_regles_non_valorisation.code = '17'::text
                LEFT JOIN pmsi.t_prestation_tarif ON t_prestations.oid = t_prestation_tarif.prestation_id AND
                    p_rsf_detail.date_fin BETWEEN t_prestation_tarif.date_debut AND t_prestation_tarif.date_fin AND 
                    t_prestation_tarif.type_ets = '2'
                WHERE 1=1
                    AND pat_benef_cmu != '1'
                    AND t_prestations.oid = ANY (ARRAY(SELECT to_id FROM pmsi.v_listes_contenu_1 WHERE liste_code = 'CTI_OVA_2QMNTPU')::bigint[])
                    AND p_rsf_detail.date_debut >= '20130101'
                    AND p_rsf_detail.prix_unitaire != t_prestation_tarif.tarif
                        ;";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
        commit_trans();

        // Lettres clé non prise en compte
        // Modif de CLA du 09-11-2015 : La lettre clé PB semble être désormais prise en compte depuis 2015
        $sqlcmd = "INSERT INTO w_non_valorises
            SELECT p_rsf_detail.CTID AS fromCTID, p_rsf_detail.rss_id, COALESCE(t_regles_non_valorisation.oid, 0) as regle_id
            FROM temp.p_rsf_detail
			JOIN temp.p_rss ON p_rsf_detail.rss_id = p_rss.oid
            JOIN pmsi.t_prestations ON prestation_id = t_prestations.oid 
            JOIN pmsi.t_listes ON t_listes.code = 'CTI_OVA_LCNPC'
            JOIN pmsi.t_listes_contenu ON t_listes_contenu.liste_id = t_listes.oid AND t_listes_contenu.to_id = t_prestations.oid
            LEFT JOIN pmsi.t_regles_non_valorisation ON t_regles_non_valorisation.code = '09'::text
			WHERE t_prestations.code NOT IN ('MPC','MCC') OR
				t_prestations.code = 'MPC' AND p_rss.date_sortie < '20190701' OR
				t_prestations.code = 'MCC' AND p_rss.date_sortie < '20190101'
                
            UNION
            
            SELECT p_rsf_detail.CTID AS fromCTID, p_rsf_detail.rss_id, COALESCE(t_regles_non_valorisation.oid, 0) as regle_id
            FROM temp.p_rsf_detail
            JOIN pmsi.t_prestations ON prestation_id = t_prestations.oid
            LEFT JOIN pmsi.t_regles_non_valorisation ON t_regles_non_valorisation.code = '09'::text
            WHERE t_prestations.code = 'PB'
                and date_debut < '20150301'";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
        commit_trans();
        
        // Prélèvement d'organes sur patients décédés, seul les PO sont valorisés
        $sqlcmd = "INSERT INTO w_non_valorises
            SELECT p_rsf_detail.CTID AS fromCTID, p_rsf_detail.rss_id, COALESCE(t_regles_non_valorisation.oid, 0) as regle_id
                FROM temp.p_rsf_detail
                JOIN temp.p_vidhosp ON p_rsf_detail.rss_id = p_vidhosp.rss_id
                JOIN pmsi.t_prestations ON prestation_id = t_prestations.oid
                LEFT JOIN pmsi.t_regles_non_valorisation ON t_regles_non_valorisation.code = '11'::text
                WHERE p_vidhosp.prelevement_organe = '1' AND
                    t_prestations.code NOT IN ('PO1', 'PO2', 'PO3', 'PO4', 'PO5', 'PO6', 'PO7', 'PO8', 'PO9', 'POA') ";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
        commit_trans();
        
        // SE en double
        // On part du principe qu'on ne garde qu'un SEh s'il y en a plusieurs
        // $sqlcmd = "INSERT INTO w_non_valorises
        //     SELECT 
        //         p_rsf_detail.CTID as fromCTID, p_rsf_detail.rss_id, COALESCE(t_regles_non_valorisation.oid, 0) as regle_id
        //     FROM
        //         temp.p_rsf_detail
        //         JOIN pmsi.t_prestations ON prestation_id = t_prestations.oid 
        //         LEFT JOIN pmsi.t_regles_non_valorisation ON t_regles_non_valorisation.code = '12'::text
        //         JOIN (
        //             SELECT 
        //                 p_rsf_detail.rss_id,
        //                 t_prestations.code as prestation_code,
        //                 min(p_rsf_detail.CTID) as CTIDmin
        //             FROM 
        //                 temp.p_rsf_detail 
        //                 JOIN pmsi.t_prestations on t_prestations.oid = p_rsf_detail.prestation_id
        //             WHERE 
        //                 t_prestations.code IN ('SE1', 'SE2', 'SE3', 'SE4', 'SE5', 'SE6', 'SE7') 
        //             GROUP by p_rsf_detail.rss_id,t_prestations.code 
        //             HAVING count(*) > 1
        //         ) subview ON subview.rss_id = p_rsf_detail.rss_id and t_prestations.code = subview.prestation_code
        //     WHERE 1=1
        //         AND p_rsf_detail.CTID <> subview.CTIDmin;";
        // $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
        // commit_trans();
        
        // AMI (AMI F et AMI N également) non valorisés à partir de M10 2015 s'ils sont présents en même temps q'un SE/FFM/ATU/APE sur une facture
        $sqlcmd = "
            WITH w_ami AS (
                (
                    SELECT 
                        rss_id
                    FROM
                        temp.p_rsf_detail
                        JOIN pmsi.t_prestations ON t_prestations.oid = p_rsf_detail.prestation_id
                    WHERE
                        t_prestations.code LIKE 'AMI%'
                        AND date_debut >= '20151001'
                    GROUP BY 1
                )
                INTERSECT
                (
                    SELECT 
                        rss_id
                    FROM
                        temp.p_rsf_detail
                        JOIN pmsi.t_prestations ON t_prestations.oid = p_rsf_detail.prestation_id
                    WHERE
                        t_prestations.code IN ('SE1', 'SE2', 'SE3', 'SE4', 'SE5', 'SE6', 'SE7', 'FFM', 'ATU', 'APE')
                        AND date_debut >= '20151001'
                    GROUP BY 1
                )
            )
            INSERT INTO w_non_valorises
            SELECT
                p_rsf_detail.CTID as from_CTID
                ,p_rsf_detail.rss_id
                ,COALESCE(t_regles_non_valorisation.oid, 0) as regle_id
            FROM
                temp.p_rsf_detail
                JOIN pmsi.t_prestations ON t_prestations.oid = p_rsf_detail.prestation_id
                JOIN w_ami ON w_ami.rss_id = p_rsf_detail.rss_id
                LEFT JOIN pmsi.t_regles_non_valorisation ON t_regles_non_valorisation.code = '13'::text
            WHERE
                t_prestations.code LIKE 'AMI%'";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
        commit_trans();
        
        
        // 15 : ACE en activité libérale
        $sqlcmd = "INSERT INTO w_non_valorises
            SELECT 
                p_rsf_detail.CTID AS fromCTID, p_rsf_detail.rss_id, COALESCE(t_regles_non_valorisation.oid, 0) as regle_id
            FROM 
                temp.p_rsf_detail
                JOIN temp.p_rsf_total ON p_rsf_total.rss_id = p_rsf_detail.rss_id
                JOIN base.t_motif_non_facturation ON motif_non_facturation_id = t_motif_non_facturation.oid
                LEFT JOIN pmsi.t_regles_non_valorisation ON t_regles_non_valorisation.code = '15'::text
                WHERE 1=1
                    AND p_rsf_detail.type = 'C'
                    AND t_motif_non_facturation.code = '6';";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
        commit_trans();
        
        // Si une lettre clé est hors période, on dégage toutes les autres regles de cette letre clé car ces controles ne sont pas pris en compte par la suite
        $sqlcmd = " WITH w_hors_periode AS (
                        SELECT 
                            fromCTID as tid_to_delete
                        FROM 
                            w_non_valorises
                            JOIN pmsi.t_regles_non_valorisation ON t_regles_non_valorisation.oid = w_non_valorises.regle_id
                        WHERE
                            t_regles_non_valorisation.code = '16'
                    )
                    DELETE FROM w_non_valorises
                    USING pmsi.t_regles_non_valorisation, w_hors_periode
                    WHERE 1=1
                        AND w_non_valorises.fromCTID = w_hors_periode.tid_to_delete
                        AND t_regles_non_valorisation.oid = w_non_valorises.regle_id
                        AND t_regles_non_valorisation.code != '16';";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
        commit_trans();

        // Ajout à la table des non valorises pour trace
        $sqlcmd = "INSERT INTO temp.p_rsf_detail_non_valorise(
                        finess, no_rss, nature, mt, dmt, date_debut, date_fin, nombre, 
                        coefficient, prix_unitaire, base_remboursement, taux_remboursement, 
                        sejour_facture, sejour_remboursable, compteur, ligne_t2a, pec_fj, 
                        coefficient_mco, sejour_remboursable_2, ghs_id, sejour_rembourse_noemie, 
                        nature_noemie, prestation_id, rss_id, type, coefficient_geo, 
                        est_ligne_rss, est_ligne_rum, no_rum, unite_medicale_id, base_remboursement_rum, 
                        montant_supplement_nf, sejour_remboursable_rum, pec_fj_id, base_remboursement_sauf_transition, 
                        base_remboursement_rum_sauf_transition, regle_id, coefficient_pacte_resp, no_ligne)
                    SELECT
                        finess, no_rss, nature, mt, dmt, date_debut, date_fin, nombre, 
                        coefficient, prix_unitaire, base_remboursement, taux_remboursement, 
                        sejour_facture, sejour_remboursable, compteur, ligne_t2a, pec_fj, 
                        coefficient_mco, sejour_remboursable_2, ghs_id, sejour_rembourse_noemie, 
                        nature_noemie, prestation_id, p_rsf_detail.rss_id, type, coefficient_geo, 
                        est_ligne_rss, est_ligne_rum, no_rum, unite_medicale_id, base_remboursement_rum, 
                        montant_supplement_nf, sejour_remboursable_rum, pec_fj_id, base_remboursement_sauf_transition, 
                        base_remboursement_rum_sauf_transition, w_non_valorises.regle_id, coefficient_pacte_resp, no_ligne
                    FROM temp.p_rsf_detail
                        JOIN w_non_valorises ON w_non_valorises.fromCTID = p_rsf_detail.CTID;";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
        commit_trans();
        if ($toResult !== FALSE) {
            echo " : " . pg_affected_rows($toResult) . " lettre(s) clé(s) non valorisée(s)" ;
        }

        // Suppression de la table des prestations
        $sqlcmd = "DELETE FROM temp.p_rsf_detail
                WHERE CTID IN (
                                SELECT fromCTID
                                FROM w_non_valorises
                                JOIN temp.p_rsf_detail ON w_non_valorises.fromCTID = p_rsf_detail.CTID
                                JOIN pmsi.t_prestations ON t_prestations.oid = p_rsf_detail.prestation_id
                                WHERE t_prestations.code not in ('ATU','FFM')
                                )
                ;";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
        commit_trans(); 

        // Suppression doublons dans non valorise
        $sqlcmd = "DELETE FROM temp.p_rsf_detail_non_valorise
        USING
        (
        SELECT rss_id, no_ligne, count(*), (MAX(ARRAY[regle_id::text,p_rsf_detail_non_valorise.CTID::text]))[2]::text AS keep_ctid
        FROM temp.p_rsf_detail_non_valorise
        GROUP BY 1,2
        HAVING count(*) > 1
        ) subview
        WHERE p_rsf_detail_non_valorise.rss_id = subview.rss_id AND
            p_rsf_detail_non_valorise.no_ligne = subview.no_ligne AND
            p_rsf_detail_non_valorise.CTID::text <> keep_ctid;";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
        commit_trans(); 

                    
    }
        
    
// Sur public, génération forfait PAT
// Sur externes sans SE ou ATU, actes >= 120 euros
    if ($ENV_TYPEETS != "1") {
        // Transformation PAT de RAFAEL en PAE
        $sqlcmd = "UPDATE temp.p_rsf_detail
                SET prestation_id = t_prestations_pae.oid
                FROM pmsi.t_prestations,
                    pmsi.t_prestations t_prestations_pae
                WHERE t_prestations.oid = p_rsf_detail.prestation_id AND
                    t_prestations.code = 'PAT' AND
                    t_prestations_pae.code = 'PAE'";
        $toResult = execute_sql($sqlcmd, $nbE);
        commit_trans();

        
        
        // Génération PAT restant
        $sqlcmd = "DROP TABLE IF EXISTS w_rsf_forfait;
                CREATE TEMP TABLE w_rsf_forfait as 
                SELECT p_rsf_detail.rss_id
                FROM temp.p_rsf_detail
                JOIN temp.p_rss on p_rss.oid = p_rsf_detail.rss_id and import_id = $import_id
                JOIN pmsi.t_prestations On prestation_id = t_prestations.oid
                WHERE type = 'B' AND 
                    t_prestations.code IN ('SE1', 'SE2', 'SE3', 'SE4', 'SE5', 'SE6', 'SE7', 'ATU', 'PAT', 'APE', 'AP2', 'FPI')
                GROUP BY 1;
                ";
        $toResult = execute_sql($sqlcmd, $nbE);
        commit_trans();
        
        $sqlcmd = "INSERT INTO temp.p_rsf_detail(  
                finess, no_rss, nature, mt, dmt, date_debut, date_fin, nombre,   
                coefficient, prix_unitaire, base_remboursement, taux_remboursement,   
                sejour_facture, sejour_remboursable, compteur, ligne_t2a, pec_fj, pec_fj_id,   
                coefficient_mco, sejour_remboursable_2, ghs_id, sejour_rembourse_noemie,   
                nature_noemie, prestation_id, rss_id, type, coefficient_geo, est_ligne_rss, est_ligne_rum, no_rum, unite_medicale_id, base_remboursement_rum)   
            SELECT subview.finess, subview.no_rss, '', '', '', subview.date_entree, subview.date_sortie,   
                -1 AS nombre,  
                1,   
                subview.montant_pat AS prix_unitaire,  
                0 - subview.montant_pat AS base_remboursement, 100, 0 - subview.montant_pat, 0 - subview.montant_pat, '', '', '', 0, 1, 0, 0, 0, '', prestation_pat_id, subview.rss_id, 'B', 
                1,  '1', '0', 0, 0, 0

            FROM (  
                SELECT p_rsf_detail.rss_id, 
                    p_rss.no_rss, 
                    date_entree, 
                    date_sortie, 
                    t_prestations_pat.oid AS prestation_pat_id,
                    p_rss.finess,
                    24 as montant_pat,
                    MAX(t_prestations.code) AS prestation_code
                FROM temp.p_rsf_detail
                    JOIN temp.p_rss on p_rss.oid = p_rsf_detail.rss_id AND traitement_epmsi = '30'
                    JOIN temp.p_rsf_total on p_rsf_detail.rss_id = p_rsf_total.rss_id
                    JOIN base.t_pec ON code_pec_id = t_pec.oid
                    JOIN base.t_exoneration_tm ON exoneration_tm_id = t_exoneration_tm.oid
                    JOIN pmsi.t_prestations ON prestation_id = t_prestations.oid
                    JOIN pmsi.t_prestations t_prestations_pat On t_prestations_pat.code = 'PAT'
                    LEFT JOIN w_rsf_forfait on w_rsf_forfait.rss_id = p_rsf_detail.rss_id
                WHERE type = 'C' AND 
                    t_exoneration_tm.code NOT IN ('1','2','3','4','5','9') AND 
                    t_prestations.code IN ('ACO', 'ADA', 'ADC', 'ADE', 'ATM',
                        'K' , 'K   F', 'K   N', 
                        'KC' , 'KC  F', 'KC  N', 'KC  U',
                        'KE' , 'KE  F', 'KE  N', 
                        'SF' , 'SF  F', 'SF  N', 'KE', 'VDE'
                        ) AND 
                    w_rsf_forfait.rss_id IS NULL AND
                    pat_benef_cmu IS DISTINCT FROM '1' AND
                    t_pec.code = '1' AND
                    p_rsf_detail.base_remboursement >= 120 
                GROUP BY 1,2,3,4,5,6,7
            ) subview;";
        $toResult = execute_sql($sqlcmd, $nbE);
        commit_trans();
    }

    analyse_table_temp("p_rss_lpp");
    analyse_table_temp("p_rss_ucd");
    analyse_table_temp("p_rss_actes");
    
    
    logInfoMsg("$nbW_total factures créées");
    logInfoMsg("$nbW_detail prestations créées");
    logInfoMsg("$nbW_lpp LPP créés");
    logInfoMsg("$nbW_ucd UCD créés");
    logInfoMsg("$nbW_actes actes créés");
    
    $nbW = $nbW_total + $nbW_detail + $nbW_lpp + $nbW_ucd + $nbW_actes;

    
    logInfoMsg("FIN GENERATION DES RSF. $nb lus, $nbW écrits, $nbE erreurs.");

    
}

function generation_fichcomp() {

    global $import_id;
    global $ENV_TYPEETS;

    global $file_RSS;
    global $file_FCP;

    global $file_exists_RSS;
    global $file_exists_FCP;

    if (! $file_exists_FCP) {
        return;
    }

    logInfoMsg("GENERATION FICHCOMP");
    
    $rssadms_array = array();
    
    begin_trans();
    

    $nb = 0;
    $nbW = 0;
    $nb_rsf = 0;
    $nbW_total = 0;
    $nbW_detail = 0;
    $nbW_lpp = 0;
    $nbW_ucd = 0;
    $nbW_actes = 0;
    $nbE = 0;
    $no_ligne = 0;

    if ($file_exists_RSS) {
        $handle = @fopen($file_RSS, "r");
        if ($handle) {
            while (!feof($handle)) {
                $buffer = fgets($handle, 99999);
                
                $no_ligne++;
                if (trim($buffer) != "" && $no_ligne < 100000000000) {
                
                    $nb++;
                    
                    $BUF_record = read_rum_partial_line($buffer);
                    
                    if ($BUF_record["type_enregistrement"] == "RUM") {

                        if (controle_check_num($BUF_record["no_sejour_administratif"],0,FALSE,$erreur,$commentaire)) {
                            $no_rss = get_numrss($BUF_record["no_rss"]);
                            $no_sejour_administratif = get_charAsNum($BUF_record["no_sejour_administratif"]);
                            $rssadms_array[$no_sejour_administratif] = $no_rss;
                        }
                        
                    }
                    
                }
                
            }
            
        }
    }
    
    
    commit_trans();
    
    
    $sqlcmd_insert_lpp = "INSERT INTO temp.p_rss_lpp( ";
    $sqlcmd_insert_lpp = $sqlcmd_insert_lpp . "rss_id,  ";
    $sqlcmd_insert_lpp = $sqlcmd_insert_lpp . "finess, ";
    $sqlcmd_insert_lpp = $sqlcmd_insert_lpp . "no_rss, ";
    $sqlcmd_insert_lpp = $sqlcmd_insert_lpp . "rang, ";
    $sqlcmd_insert_lpp = $sqlcmd_insert_lpp . "date_lpp, ";
    $sqlcmd_insert_lpp = $sqlcmd_insert_lpp . "lpp_id, ";
    $sqlcmd_insert_lpp = $sqlcmd_insert_lpp . "nombre, ";
    $sqlcmd_insert_lpp = $sqlcmd_insert_lpp . "prix_unitaire, ";
    $sqlcmd_insert_lpp = $sqlcmd_insert_lpp . "montant_facture, non_pris_en_compte";
    $sqlcmd_insert_lpp = $sqlcmd_insert_lpp . ") ";
    
    $sqlcmd_insert_ucd = "INSERT INTO temp.p_rss_ucd(
            finess, no_rss, rang, date_ucd, ucd_id, nombre, coefficient_fractionnement, 
            prix_unitaire_achat, prix_unitaire_ecart_indemnisable, montant_ecart_indemnisable, 
            montant_facture, rss_id, non_pris_en_compte, type_ucd_id, indication) ";
    
    
    
    
    // Génération
    $nb = 0;
    $no_ligne = 0;
    $rss_id = 0;
    
    $handle = @fopen($file_FCP, "r");
    if ($handle) {
        while (!feof($handle)) {
            $buffer = fgets($handle, 99999);
            
            $no_ligne++;
            if (trim($buffer) != "" && $no_ligne < 100000000000 ) {
            
                $nb++;
                
                $BUF_record = read_fcp_line($buffer);
                
                // Controle si ligne acceptée par GENRSA
                if (check_complog_fichcomp($buffer, $gravite, $erreur, $commentaire)) {

                    // Génération
                    if ($BUF_record["ok"] == TRUE && $BUF_record["type_enregistrement"] == "02") {
                        

                                $rss_id = 0;
                                $no_rss = 0;
                                
                                if (controle_check_num($BUF_record["no_sejour_administratif"],0,FALSE,$erreur,$commentaire)) {
                                    $no_sejour_administratif = get_charAsNum($BUF_record["no_sejour_administratif"]);
                                    $no_rss = @$rssadms_array[$no_sejour_administratif];
                                    $no_rss = get_numrss($no_rss);
                                    if ($no_rss > 0) {
                                        $rss_id = get_rss($no_rss);
                                    }
                                }
                                
                                if ($rss_id > 0) {

                                    $finess = $BUF_record["finess"];
                                    $no_rss = $no_rss;
                                    $rang = ""; 
                                    $date_lpp = sqlDate($BUF_record["date_debut"]); 
                                    if (!controle_check_date($BUF_record["date_debut"],$none,$none)) {
                                        $date_lpp = "2099-12-31";
                                    }
                                    $lpp_id = 0;
                                    $nombre = get_num($BUF_record["nombre"],1); 
                                    if ($nombre == 0) {
                                        $nombre = 1;
                                    }
                                    $montant_facture = round(get_num($BUF_record["montant_paye"]) / 1000,2);
                                    $prix_unitaire = round($montant_facture / $nombre,2);

                                    $lpp_id = get_lpp($BUF_record["code"]);
                                    
                                    $sqlcmd = "$sqlcmd_insert_lpp VALUES( $rss_id,  '$finess',  $no_rss,  '$rang', '$date_lpp', $lpp_id, $nombre, $prix_unitaire, $montant_facture, '0') ";

                                    $toResult = execute_sql($sqlcmd, $nbE, $nbW_lpp );
                            

                                }

                    
                    }
                
                    if ($BUF_record["ok"] == TRUE && ($BUF_record["type_enregistrement"] == "01" || $BUF_record["type_enregistrement"] == "06" || $BUF_record["type_enregistrement"] == "09")) {
                    

                                $rss_id = 0;
                                $no_rss = 0;
                            
                                if (controle_check_num($BUF_record["no_sejour_administratif"],0,FALSE,$erreur,$commentaire)) {
                                    $no_sejour_administratif = get_charAsNum($BUF_record["no_sejour_administratif"]);
                                    $no_rss = @$rssadms_array[$no_sejour_administratif];
                                    $no_rss = get_numrss($no_rss);
                                    if ($no_rss > 0) {
                                        $rss_id = get_rss($no_rss);
                                    }
                                }

                            
                        if ($rss_id > 0) {
                        if (get_num($BUF_record["code"]) > 0) {

                                    $finess = $BUF_record["finess"];
                                    $no_rss = $no_rss;
                                    $rang = ""; 
                                    $date_ucd = sqlDate($BUF_record["date_debut"]); 
                                    if (!controle_check_date($BUF_record["date_debut"],$none,$none)) {
                                        $date_ucd = "2099-12-31";
                                    }
                                    $ucd_id = 0;
                                    $nombre = get_num($BUF_record["nombre"],1) / 1000; 
                                    if ($nombre == 0) {
                                        $nombre = 1;
                                    }
                                    $montant_facture = get_num($BUF_record["montant_paye"]) / 1000;
                                    //$prix_unitaire = round($montant_facture / $nombre,2);
                                    
                                    $coefficient_fractionnement = 1;
                                    $prix_unitaire_achat = 0;
                                    $prix_unitaire_ecart_indemnisable = 0; 
                                    $montant_ecart_indemnisable = 0;
                                    
                                    $indication = $BUF_record["indication"];


                                    $ucd_id = get_ucd($BUF_record["code"]);
                                    $type_ucd_id = get_type_ucd($BUF_record["type_enregistrement"]);
                                    
                                    $sqlcmd = "$sqlcmd_insert_ucd VALUES('$finess', $no_rss, '$rang', '$date_ucd', $ucd_id, $nombre, 
                                            $coefficient_fractionnement, $prix_unitaire_achat, 
                                            $prix_unitaire_ecart_indemnisable, $montant_ecart_indemnisable, 
                                            $montant_facture, $rss_id, '0', '$type_ucd_id', upper('$indication')) ";

                                    $toResult = execute_sql($sqlcmd, $nbE, $nbW_ucd );

                                
                                    }
                                }
                                

                    }
                }
            }
        
        }
        
        fclose($handle);
    
    }
    
    // Attention, si des UCD sont sur un dossier administratif de séjour multiple (plusieurs rss pour même sejour)
    // Attribuer au bon séjour
    $sqlcmd = "UPDATE temp.p_rss_ucd
        SET rss_id = p_rss2.oid, no_rss = p_rss2.no_rss
        FROM temp.p_rss
        JOIN temp.p_rss p_rss2 ON p_rss.no_sejour_administratif = p_rss2.no_sejour_administratif AND
            p_rss.oid <> p_rss2.oid
        WHERE p_rss_ucd.rss_id = p_rss.oid AND
            date_ucd NOT BETWEEN p_rss.date_entree and p_rss.date_sortie AND
            date_ucd BETWEEN p_rss2.date_entree and p_rss2.date_sortie;";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    if ($ENV_TYPEETS != '1') {

		// Si radiation, la date de fin correspond à la date de radiation. Donc on enleve 1 à la date de fin
		$sqlcmd = "
		DROP TABLE IF EXISTS w_lpp_tarifs;
            CREATE TEMP TABLE w_lpp_tarifs AS
            SELECT t_lpp_tarifs.*, 
		CASE WHEN t_lpp_tarifs.date_fin < '20991231' AND
			t_lpp_tarifs_next.rang IS NULL THEN '1'::text ELSE '0'::text END AS is_last
            FROM pmsi.t_lpp_tarifs
            JOIN pmsi.t_lpp ON t_lpp_tarifs.lpp_id = t_lpp.oid
            LEFT JOIN pmsi.t_lpp_tarifs t_lpp_tarifs_next ON
		t_lpp_tarifs.lpp_id = t_lpp_tarifs_next.lpp_id AND
		t_lpp_tarifs.rang = t_lpp_tarifs_next.rang + 1 
		;

		UPDATE w_lpp_tarifs
		SET date_fin = date_fin - interval '1 day'
		WHERE is_last = '1'
		;
		
		ANALYSE w_lpp_tarifs
		;";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );
        commit_trans();

        
        // CLA le 30-05-2016 : Non pris en compte si montant FICHCOMP = 0
        $sqlcmd = "UPDATE temp.p_rss_lpp
        SET non_pris_en_compte = '1'
        FROM
            temp.p_rss
        WHERE 1=1
            AND p_rss.oid = p_rss_lpp.rss_id
            AND p_rss.import_id = $import_id
            AND (p_rss_lpp.prix_unitaire = 0 OR montant_facture = 0)
            AND p_rss_lpp.date_lpp >= '20140101'
            AND non_pris_en_compte != '1'";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );
        commit_trans();
        
        $sqlcmd = "UPDATE temp.p_rss_lpp
        SET non_pris_en_compte = '1'
        FROM
        (
            SELECT subview.rss_id, subview.lpp_id FROM
            (
                SELECT rss_id, lpp_id, date_lpp, t_lpp.code FROM temp.p_rss, temp.p_rss_lpp, pmsi.t_lpp
                WHERE p_rss.import_id = $import_id AND p_rss.oid = p_rss_lpp.rss_id AND lpp_id = t_lpp.oid
            ) subview LEFT JOIN w_lpp_tarifs t_lpp_tarifs ON (subview.lpp_id = t_lpp_tarifs.lpp_id AND subview.date_lpp BETWEEN t_lpp_tarifs.date_debut AND t_lpp_tarifs.date_fin)
            where prix_unitaire is null
        ) subview
        WHERE p_rss_lpp.rss_id = subview.rss_id AND p_rss_lpp.lpp_id = subview.lpp_id AND
            p_rss_lpp.date_lpp >= '20140101'";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );
        commit_trans();
        
        // Montants Tarif responsabilité et t2a accodee (LPP)
        
        $sqlcmd = "UPDATE temp.p_rss_lpp
                    SET prix_unitaire_tr = t_lpp_tarifs.prix_unitaire,
                        montant_tr = round(p_rss_lpp.nombre * t_lpp_tarifs.prix_unitaire,3),
                        montant_t2a_accorde = 
                            round(CASE WHEN p_rss_lpp.nombre * t_lpp_tarifs.prix_unitaire - p_rss_lpp.montant_facture > 0
                            THEN p_rss_lpp.montant_facture + (p_rss_lpp.nombre * t_lpp_tarifs.prix_unitaire - p_rss_lpp.montant_facture) / 2
                            ELSE p_rss_lpp.nombre * t_lpp_tarifs.prix_unitaire END,3)

                    FROM temp.p_rss, w_lpp_tarifs t_lpp_tarifs
                    WHERE rss_id = p_rss.oid 
                        AND t_lpp_tarifs.lpp_id = p_rss_lpp.lpp_id
                        AND date_lpp  between t_lpp_tarifs.date_debut and t_lpp_tarifs.date_fin 
                        AND p_rss_lpp.montant_facture <> 0
                        AND (
                            p_rss_lpp.prix_unitaire_tr <> t_lpp_tarifs.prix_unitaire OR
                            p_rss_lpp.montant_tr <> round(p_rss_lpp.nombre * t_lpp_tarifs.prix_unitaire,3) OR
                            p_rss_lpp.montant_t2a_accorde <> 
                                round(CASE WHEN p_rss_lpp.nombre * t_lpp_tarifs.prix_unitaire - p_rss_lpp.montant_facture > 0
                                THEN p_rss_lpp.montant_facture + (p_rss_lpp.nombre * t_lpp_tarifs.prix_unitaire - p_rss_lpp.montant_facture) / 2
                                ELSE p_rss_lpp.nombre * t_lpp_tarifs.prix_unitaire END,3) OR
                            p_rss_lpp.prix_unitaire_tr IS NULL OR
                            p_rss_lpp.montant_tr IS NULL OR
                            p_rss_lpp.montant_t2a_accorde IS NULL
                        )";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );
        commit_trans();
        
        // Ecart
        $sqlcmd = "UPDATE temp.p_rss_lpp
                    SET montant_ecart_indemnisable = montant_t2a_accorde - montant_facture
                    WHERE montant_ecart_indemnisable <> montant_t2a_accorde - montant_facture AND
                        COALESCE(montant_t2a_accorde,0) <> 0";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );
        commit_trans();
        
        
        $sqlcmd = "UPDATE temp.p_rss_ucd ";
        $sqlcmd = $sqlcmd . "SET nombre = 1 ";
        $sqlcmd = $sqlcmd . "FROM temp.p_rss ";
        $sqlcmd = $sqlcmd . "WHERE  ";
        $sqlcmd = $sqlcmd . "p_rss_ucd.rss_id = p_rss.oid AND p_rss.import_id = $import_id ";
        $sqlcmd = $sqlcmd . "AND nombre = 0";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );
        commit_trans();
        
        // non pris en compte ?
        $sqlcmd = "UPDATE temp.p_rss_ucd
        SET non_pris_en_compte = '1'
        FROM
        (
            SELECT subview.rss_id, subview.ucd_id FROM
            (
                SELECT rss_id, ucd_id, date_ucd, t_ucd.code 
                FROM temp.p_rss, temp.p_rss_ucd, pmsi.t_ucd
                WHERE p_rss.import_id = $import_id AND 
                    p_rss.oid = p_rss_ucd.rss_id AND 
                    ucd_id = t_ucd.oid
            ) subview LEFT JOIN pmsi.t_ucd_tarifs ON (subview.ucd_id = t_ucd_tarifs.ucd_id 
                    AND subview.date_ucd BETWEEN t_ucd_tarifs.date_debut AND t_ucd_tarifs.date_fin 
                    AND subview.date_ucd BETWEEN t_ucd_tarifs.date_debut AND t_ucd_tarifs.top_taa_date_fin)
            where (top_taa <> '1' OR top_taa IS NULL)
        ) subview
        WHERE p_rss_ucd.rss_id = subview.rss_id AND p_rss_ucd.ucd_id = subview.ucd_id";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );
        commit_trans();
		
		// Essai thérapeuthique (montant facture = 0)
		$sqlcmd = "UPDATE temp.p_rss_ucd
		SET non_pris_en_compte = '1'
		WHERE montant_facture = 0 AND
			non_pris_en_compte <> '1'";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );
        commit_trans();
		;
		
		// ELA 18/01/2024. Association UCD/Indication bornée
		// Pas de table officielle trouvée
		// En dur dans un premier temps
        // A modifier une fois la liste officielle trouvée
		$sqlcmd = "UPDATE temp.p_rss_ucd
			SET non_pris_en_compte = '1'
			FROM pmsi.t_ucd
			WHERE ucd_id = t_ucd.oid AND
				(
				t_ucd.code = '9332620' AND indication = 'I000077' AND date_ucd NOT BETWEEN '00010101' AND '20231130' OR
				t_ucd.code = '9003261' AND indication = 'I000634' AND date_ucd < '20230901'
				)";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );
        commit_trans();
		;
        
        // AVASTIN en SUS non valorisés (p_rsa.top_radiation_partielle_avastin)
        $sqlcmd = "
            UPDATE temp.p_rss_ucd SET
                non_pris_en_compte = '1'
            FROM
                pmsi.t_type_ucd,
                temp.p_rsa,
                pmsi.t_ucd
            WHERE 1=1
                AND p_rss_ucd.type_ucd_id = t_type_ucd.oid
                AND p_rss_ucd.rss_id = p_rsa.rss_id
                AND p_rss_ucd.ucd_id = t_ucd.oid
                AND t_type_ucd.code = 'SUS'
                AND p_rsa.top_radiation_partielle_avastin = '1'
                AND t_ucd.code IN ('9261104','9261110')
                AND non_pris_en_compte != '1'";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );
        commit_trans();        
        
        // Mettre à jour les indication_id dans la table p_rss_ucd
        $sqlcmd = "
            UPDATE temp.p_rss_ucd SET
                indication_id = t_indication.oid
            FROM
                pmsi.t_indication
            WHERE 1=1
                AND p_rss_ucd.indication = t_indication.code
            ";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );
        commit_trans();
        
        // à partir du M09 2018, pour les séjours entrés après le 01/09/2018 les UCD ne sont pas valorisés si l'indication est absente dans le fichcomp MED
        // L'indication I009999 semble ne pas être valorisée
        $sqlcmd = "
            UPDATE temp.p_rss_ucd SET
                non_pris_en_compte = '1'
            FROM
                 pmsi.t_type_ucd,
                 temp.p_rss
            WHERE 1=1
                AND p_rss_ucd.rss_id = p_rss.oid
                AND p_rss_ucd.type_ucd_id = t_type_ucd.oid
                AND p_rss.date_entree >= '20180901'
                AND (trim(indication) = '' OR trim(indication) = 'I009999')
                AND t_type_ucd.code = 'SUS'
                AND non_pris_en_compte != '1'";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );
        commit_trans();
        
        // Montants Tarif responsabilité et t2a accodee (UCD)
        // Modif CLA du 2017-05-05 : les AVASTIN (ucd 9261110) sous ATU pour cancer du sein (diag C50*) doivent aussi être valorisés
        // http://www.atih.sante.fr/sites/default/files/public/content/2916/notice_technique_atih_ndeg_cim-mf-640-6-2016_radiation_partielle_avastin.pdf (page 6)
        // CLA 2019-03-08 Les UCD avec indication 'I999998' semblent ne pas récupérer les montants accordés par l'ATIH et sont valorisés avec le prix d'achat directement (à vérifier)
        $sqlcmd = " WITH w_avastin_atu AS (
                        SELECT
                            p_rss_ucd.rss_id,
                            p_rss_ucd.date_ucd,
                            p_rss_ucd.ucd_id,
                            t_ucd.code,
                            to_char(p_rss_ucd.rss_id, '999999999999') || to_char(p_rss_ucd.ucd_id, '999999999999') as key
                        FROM
                            temp.p_rss_ucd
                            JOIN pmsi.t_ucd ON t_ucd.oid = p_rss_ucd.ucd_id
                            JOIN pmsi.t_type_ucd ON t_type_ucd.oid = p_rss_ucd.type_ucd_id
                            JOIN temp.p_rss_diagnostics ON p_rss_diagnostics.rss_id = p_rss_ucd.rss_id
                            JOIN pmsi.t_diagnostics ON t_diagnostics.oid = p_rss_diagnostics.diagnostic_id
                        WHERE 1=1
                            AND t_ucd.code = '9261110'
                            AND t_type_ucd.code = 'ATU'
                            AND t_diagnostics.code like 'C50%'
                        GROUP BY 1,2,3,4,5
                    )
                    UPDATE temp.p_rss_ucd
                    SET prix_unitaire_tr = round(CASE WHEN indication = 'I999998' THEN montant_facture ELSE t_ucd_tarifs.prix_unitaire_ht * 102.10 / 100 END, 3),
                        montant_tr = round(CASE WHEN indication = 'I999998' THEN montant_facture ELSE p_rss_ucd.nombre * round(t_ucd_tarifs.prix_unitaire_ht * 102.10 / 100,3) END, 3),
                        montant_t2a_accorde = 
                            round(CASE WHEN indication = 'I999998' THEN montant_facture
                                       WHEN p_rss_ucd.nombre * round(t_ucd_tarifs.prix_unitaire_ht * 102.10 / 100,3) - p_rss_ucd.montant_facture > 0
                            THEN p_rss_ucd.montant_facture + (p_rss_ucd.nombre * round(t_ucd_tarifs.prix_unitaire_ht * 102.10 / 100,3) - p_rss_ucd.montant_facture) / 2
                            ELSE p_rss_ucd.nombre * round(t_ucd_tarifs.prix_unitaire_ht * 102.10 / 100,3) END,3)

                    FROM temp.p_rss, pmsi.t_ucd_tarifs, pmsi.t_type_ucd
                    WHERE rss_id = p_rss.oid 
                        AND t_ucd_tarifs.ucd_id = p_rss_ucd.ucd_id
                        AND date_ucd  between t_ucd_tarifs.date_debut and t_ucd_tarifs.date_fin 
                        AND p_rss_ucd.montant_facture <> 0
                        AND p_rss_ucd.type_ucd_id = t_type_ucd.oid
                        AND (t_type_ucd.code = 'SUS' OR (t_type_ucd.code = 'ATU' AND to_char(p_rss_ucd.rss_id, '999999999999') || to_char(p_rss_ucd.ucd_id, '999999999999') = ANY (ARRAY( SELECT key FROM w_avastin_atu)::text[])))
                        AND (
                            p_rss_ucd.prix_unitaire_tr <> round(CASE WHEN indication = 'I999998' THEN montant_facture ELSE t_ucd_tarifs.prix_unitaire_ht * 102.10 / 100 END, 3) OR
                            p_rss_ucd.montant_tr <> round(CASE WHEN indication = 'I999998' THEN montant_facture ELSE p_rss_ucd.nombre * round(t_ucd_tarifs.prix_unitaire_ht * 102.10 / 100,3) END, 3) OR
                            p_rss_ucd.montant_t2a_accorde <> 
                                round(CASE WHEN indication = 'I999998' THEN montant_facture
                                       WHEN p_rss_ucd.nombre * round(t_ucd_tarifs.prix_unitaire_ht * 102.10 / 100,3) - p_rss_ucd.montant_facture > 0
                                THEN p_rss_ucd.montant_facture + (p_rss_ucd.nombre * round(t_ucd_tarifs.prix_unitaire_ht * 102.10 / 100,3) - p_rss_ucd.montant_facture) / 2
                                ELSE p_rss_ucd.nombre * round(t_ucd_tarifs.prix_unitaire_ht * 102.10 / 100,3) END,3) OR
                            p_rss_ucd.prix_unitaire_tr IS NULL OR
                            p_rss_ucd.montant_tr IS NULL OR
                            p_rss_ucd.montant_t2a_accorde IS NULL
                        )";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );
        commit_trans();
		
		// Les médicaments sous ATU sont rembourses
		$sqlcmd = "UPDATE temp.p_rss_ucd SET
			non_pris_en_compte = '0',
			montant_tr = montant_facture,
			montant_t2a_accorde = montant_facture,
			prix_unitaire_tr = montant_facture / nombre
		FROM temp.p_rss, 
			pmsi.t_type_ucd
		WHERE p_rss_ucd.rss_id = p_rss.oid AND
			p_rss.en_cours = '0' AND
			p_rss_ucd.type_ucd_id = t_type_ucd.oid AND
			t_type_ucd.code = 'ATU'";
		$toResult = execute_sql($sqlcmd, $nbE, $nbW );
        commit_trans();
        
        // Ecart
        $sqlcmd = "UPDATE temp.p_rss_ucd
                    SET montant_ecart_indemnisable = montant_t2a_accorde - montant_facture
                    FROM pmsi.t_type_ucd
                    WHERE 
                        p_rss_ucd.type_ucd_id = t_type_ucd.oid AND
                        t_type_ucd.code = 'SUS' AND
                        montant_ecart_indemnisable <> montant_t2a_accorde - montant_facture AND
                        COALESCE(montant_t2a_accorde,0) <> 0";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );
        commit_trans();
    }
    
    analyse_table_temp("p_rsf_detail");
    analyse_table_temp("p_rss_lpp");
    analyse_table_temp("p_rss_ucd");
    

    logInfoMsg("$nbW_lpp LPP créés");
    logInfoMsg("$nbW_ucd UCD créés");
    
    $nbW = $nbW_detail + $nbW_lpp + $nbW_ucd;

    
    logInfoMsg("FIN GENERATION FICHCOMP. $nb lus, $nbW écrits, $nbE erreurs.");
	
    
}

function generation_fichsup() {
    
    global $import_id;
    global $file_TSP;
    global $file_exists_TSP;
    
    if (! $file_exists_TSP) {
        return;
    }
    
    logInfoMsg("GENERATION FICHSUP");
    
    begin_trans();
    
    $nb = 0;
    $nbW = 0;
    
    $sqlcmd_insert_tsp = "
        INSERT INTO temp.p_fichsup_transports (
            finess,
            type_fichier,
            annee,
            mois,
            prestation_id,
            nb_sejours,
            import_id
        ) VALUES ";
    $values = array();
    
    if ($file_exists_TSP) {
        logInfoMsg("Fichsup transports");
        $handle = fopen($file_TSP, "r");
        if ($handle) {
            while (!feof($handle)) {
                $buffer = fgets($handle, 99999);
                $no_ligne++;
                if (trim($buffer) != "" && $no_ligne < 1000000) {
                    
                    $nb++;
                    $BUF_record = read_tsp_line($buffer);
                    
                    if ($BUF_record["ok"] === TRUE && $BUF_record["type_fichier"] == "G61") {
                        $nbW++;
                        $finess = $BUF_record["finess"];
                        $type_fichier = $BUF_record["type_fichier"];
                        $annee = $BUF_record["annee"];
                        $mois = $BUF_record["periode"];
                        $prestation_id = get_prestation($BUF_record["code"]);
                        $nb_sejours = get_num($BUF_record["nb_sejours"]);
                        $values[] = "('$finess', '$type_fichier', '$annee', '$mois', $prestation_id, $nb_sejours, $import_id)";
                    }
                    // Ecriture des values par bloc de 50
                    if (count($values) > 50) {
                        $sqlcmd = $sqlcmd_insert_tsp . implode(", ", $values);
                        $toResult = execute_sql($sqlcmd);
                        $values = array();
                    }
                }
            }
        }
        fclose($handle);
        
        // Ecriture des values résiduelles
        if (count($values) > 0) {
            $sqlcmd = $sqlcmd_insert_tsp . implode(", ", $values);
            $toResult = execute_sql($sqlcmd);
            unset($sqlcmd);
            unset($values);
        }
    }
    
    commit_trans();
    analyse_table_temp("p_fichsup_transports");    
   
    logInfoMsg("FIN GENERATION FICHSUP. $nb lus, $nbW écrits");
}



function generation_valosej() {
    
    global $file_VSJ;
    global $file_exists_VSJ;
    global $import_id;
    
    if ($file_exists_VSJ) {
        logInfoMsg("Valorisation des séjours d'après VALOSEJ");
        $file_VSJ_path = realpath($file_VSJ);
        $compteur_ligne = 0;
        $raw_data = '';
        $updated_data = '';
        $temp_file = temp_file();
        if (($handle = fopen($file_VSJ_path, "r")) !== FALSE) {
            while (($raw_data = fgets($handle, 1000)) !== FALSE) {
                $compteur_ligne++;
                if (strpos($raw_data, ";") > -1) {	
					$raw_data = str_replace(";", "\t", $raw_data);
				}
                $updated_data .= str_replace("\t.\t", "\t0\t", $raw_data);
                if ($compteur_ligne > 50) {
                    file_put_contents($temp_file, $updated_data, FILE_APPEND);
                    $updated_data = '';
                    $compteur_ligne = 0;
                }
            }
            if ($compteur_ligne > 0) {
                file_put_contents($temp_file, $updated_data, FILE_APPEND);
                $compteur_ligne = 0;
            }
            fclose($handle);
        }
        
        // $file_VSJ_path = str_replace('\\','/',$file_VSJ_path);
        $file_VSJ_path = str_replace('\\','/',$temp_file);
        $sqlcmd = "SELECT pmsi.cti_gen_valosej('$file_VSJ_path', 'temp', $import_id)";
        $toResult = execute_sql($sqlcmd);
        unlink($temp_file);
    }
    else {
        logWarnMsg("Fichier VALOSEJ absent");
    }
}


function generation_valoace() {
    
    global $file_VSE;
    global $file_exists_VSE;
    global $import_id;
    
    if ($file_exists_VSE) {
        logInfoMsg("Valorisation des ACE d'après VALOACE");
        $file_VSE_path = realpath($file_VSE);
        $compteur_ligne = 0;
        $raw_data = '';
        $updated_data = '';
        $temp_file = temp_file();
        if (($handle = fopen($file_VSE_path, "r")) !== FALSE) {
            while (($raw_data = fgets($handle, 1000)) !== FALSE) {
                $compteur_ligne++;
                if (strpos($raw_data, ";") > -1) {	
					$raw_data = str_replace(";", "\t", $raw_data);
				}
                $updated_data .= str_replace("\t.\t", "\t0\t", $raw_data);
                if ($compteur_ligne > 50) {
                    file_put_contents($temp_file, $updated_data, FILE_APPEND);
                    $updated_data = '';
                    $compteur_ligne = 0;
                }
            }
            if ($compteur_ligne > 0) {
                file_put_contents($temp_file, $updated_data, FILE_APPEND);
                $compteur_ligne = 0;
            }
            fclose($handle);
        }
        
        // $file_VSJ_path = str_replace('\\','/',$file_VSJ_path);
        $file_VSE_path = str_replace('\\','/',$temp_file);
        $sqlcmd = "SELECT pmsi.cti_gen_valoace('$file_VSE_path', 'temp', $import_id)";
        $toResult = execute_sql($sqlcmd);
        unlink($temp_file);
    }
    else {
        logWarnMsg("Fichier VALOACE absent");
    }
}


function valorisation_public() {

    global $import_id;
	
    global $file_FCP;
    
    global $file_exists_VSJ;
    global $file_exists_FCP;
    global $ENV_TYPEETS;
    global $iCTI_connexion;
    global $annee_fin;


    logInfoMsg("VALORISATION GHS");

    $nbE = 0;

    
    // GHS dans RSS
    logInfoMsg("Génération GHS selon GHM");
    
    // RSA par RSS
    $sqlcmd = "DROP TABLE IF EXISTS w_rss_rsa;
        CREATE TEMP TABLE w_rss_rsa AS
        SELECT 
            p_rss.oid AS rss_rsa_rss_id,
            p_rss.ghm_id AS rss_rsa_ghm_id,
            p_rss.ghs_id AS rss_rsa_ghs_id,
            p_rsa.rss_id AS rss_rsa_id_ok
        FROM
            temp.p_rss
            LEFT JOIN temp.p_rsa ON p_rss.oid = p_rsa.rss_id
        WHERE import_id = $import_id AND p_rss.ghm_id <> 0;
    
        CREATE INDEX w_rss_rsa_i1 ON w_rss_rsa USING btree (rss_rsa_rss_id);
    ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();

        
    // Si RSA,
    // Remplacer GHM et GHS par ceux de GENRSA
    $sqlcmd = "UPDATE temp.p_rss 
        SET 
            ghm_id = p_rsa.ghm_genrsa_id,
            ghs_id = p_rsa.ghs_genrsa_id,
            code_retour_groupage = p_rsa.code_retour_genrsa
        FROM temp.p_rsa
        WHERE import_id = $import_id
        AND p_rss.oid = p_rsa.rss_id AND 
            (p_rss.ghs_id <> p_rsa.ghs_genrsa_id 
             OR p_rss.ghm_id <> p_rsa.ghm_genrsa_id
             OR code_retour_groupage <> p_rsa.code_retour_genrsa) ";
        
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
    
    // GHS dans RSF DETAIL
    logInfoMsg("Valorisation GHS");
    
    /*
        Modif de CLA le 06-11-2015
        Pour le GHM 9626 de préparation aux scéances d'irradiation, OVALIDE ne valorise qu'une seule séance même si le RSS a la variable nb_seances > 1
    */
    $sqlcmd = "INSERT INTO temp.p_rsf_detail( 
                finess, no_rss, nature, mt, dmt, date_debut, date_fin, nombre,  
                coefficient, prix_unitaire, base_remboursement, taux_remboursement,  
                sejour_facture, sejour_remboursable, compteur, ligne_t2a, pec_fj, pec_fj_id,  
                coefficient_mco, sejour_remboursable_2, ghs_id, sejour_rembourse_noemie,  
                nature_noemie, prestation_id, rss_id, type, coefficient_geo, est_ligne_rss, est_ligne_rum, no_rum, unite_medicale_id, base_remboursement_rum) 
                SELECT  
                finess, no_rss, '' as nature, '' as mt, '' as dmt, date_entree as date_debut, date_sortie as date_fin, 
                CASE WHEN nb_seances <= 1 OR t_ghs.code IN (9626, 9628, 9630) THEN 1 ELSE nb_seances END as nombre,  
                1 as coefficient,  
                CASE 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_1 AND p_rss.date_sortie <= t_ghs.date_fin_public_1 THEN t_ghs.tarif_ghs_public_1 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_2 AND p_rss.date_sortie <= t_ghs.date_fin_public_2 THEN t_ghs.tarif_ghs_public_2 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_3 AND p_rss.date_sortie <= t_ghs.date_fin_public_3 THEN t_ghs.tarif_ghs_public_3 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_4 AND p_rss.date_sortie <= t_ghs.date_fin_public_4 THEN t_ghs.tarif_ghs_public_4 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_5 AND p_rss.date_sortie <= t_ghs.date_fin_public_5 THEN t_ghs.tarif_ghs_public_5 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_6 AND p_rss.date_sortie <= t_ghs.date_fin_public_6 THEN t_ghs.tarif_ghs_public_6 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_7 AND p_rss.date_sortie <= t_ghs.date_fin_public_7 THEN t_ghs.tarif_ghs_public_7 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_8 AND p_rss.date_sortie <= t_ghs.date_fin_public_8 THEN t_ghs.tarif_ghs_public_8 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_9 AND p_rss.date_sortie <= t_ghs.date_fin_public_9 THEN t_ghs.tarif_ghs_public_9 
                ELSE 0::numeric 
                END 
                as prix_unitaire, 0 as base_remboursement, 0 as taux_remboursement,  
                0 as sejour_facture, 0 as sejour_remboursable, '' as compteur, '' as ligne_t2a, '' as pec_fj, 0 as pec_fj_id,  
                1 as coefficient_mco, 0 as sejour_remboursable_2, p_rss.ghs_id as ghs_id, 0 as sejour_rembourse_noemie,  
                '' as nature_noemie, t_prestations.oid as prestation_id, p_rss.oid as rss_id, 'B',
                1,  '1', '0', 0, 0, 0
                FROM temp.p_rss,
                    pmsi.t_prestations, pmsi.t_ghs , pmsi.t_ghm
                WHERE import_id = $import_id 
                AND t_prestations.code = 'GHS' 
                AND p_rss.ghm_id > 0 AND p_rss.ghs_id = t_ghs.oid AND p_rss.ghm_id = t_ghm.oid 
                AND p_rss.oid NOT IN (SELECT rss_id FROM temp.p_rsf_detail WHERE prestation_id IN (SELECT oid FROM pmsi.t_prestations WHERE code = 'GHS')) ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
    
    // génération EXH si RSA
    $sqlcmd = "INSERT INTO temp.p_rsf_detail(  
                finess, no_rss, nature, mt, dmt, date_debut, date_fin, nombre,   
                coefficient, prix_unitaire, base_remboursement, taux_remboursement,   
                sejour_facture, sejour_remboursable, compteur, ligne_t2a, pec_fj, pec_fj_id,   
                coefficient_mco, sejour_remboursable_2, ghs_id, sejour_rembourse_noemie,   
                nature_noemie, prestation_id, rss_id, type, coefficient_geo, est_ligne_rss, est_ligne_rum, no_rum, unite_medicale_id, base_remboursement_rum)   
                SELECT   
                p_rss.finess, p_rss.no_rss, '' as nature, '' as mt, '' as dmt, p_rss.date_entree as date_debut, p_rss.date_sortie as date_fin,  
                p_rsa.nb_exh,   
                1 as coefficient,   
                CASE  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_1 AND p_rss.date_sortie <= t_ghs.date_fin_public_1 THEN t_ghs.tarif_exh_public_1  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_2 AND p_rss.date_sortie <= t_ghs.date_fin_public_2 THEN t_ghs.tarif_exh_public_2  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_3 AND p_rss.date_sortie <= t_ghs.date_fin_public_3 THEN t_ghs.tarif_exh_public_3  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_4 AND p_rss.date_sortie <= t_ghs.date_fin_public_4 THEN t_ghs.tarif_exh_public_4  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_5 AND p_rss.date_sortie <= t_ghs.date_fin_public_5 THEN t_ghs.tarif_exh_public_5  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_6 AND p_rss.date_sortie <= t_ghs.date_fin_public_6 THEN t_ghs.tarif_exh_public_6  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_7 AND p_rss.date_sortie <= t_ghs.date_fin_public_7 THEN t_ghs.tarif_exh_public_7  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_8 AND p_rss.date_sortie <= t_ghs.date_fin_public_8 THEN t_ghs.tarif_exh_public_8  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_9 AND p_rss.date_sortie <= t_ghs.date_fin_public_9 THEN t_ghs.tarif_exh_public_9  
                ELSE 0::numeric  
                END  
                as prix_unitaire, 0 as base_remboursement, 0 as taux_remboursement,   
                0 as sejour_facture, 0 as sejour_remboursable, '' as compteur, '' as ligne_t2a, '' as pec_fj, 0 as pec_fj_id,   
                1 as coefficient_mco, 0 as sejour_remboursable_2, p_rss.ghs_id as ghs_id, 0 as sejour_rembourse_noemie,   
                '' as nature_noemie, t_prestations.oid as prestation_id, p_rss.oid as rss_id, 'B', 
                1,  '1', '0', 0, 0, 0  
                FROM temp.p_rss, temp.p_rsa, pmsi.t_prestations, pmsi.t_ghs  
                WHERE import_id = $import_id
                AND p_rsa.rss_id = p_rss.oid
                AND t_prestations.code = 'EXH'  
                AND p_rss.ghm_id > 0 AND p_rss.ghs_id = t_ghs.oid  
                AND p_rss.oid NOT IN (SELECT rss_id FROM temp.p_rsf_detail WHERE prestation_id IN (SELECT oid FROM pmsi.t_prestations WHERE code = 'EXH')) 
                AND p_rsa.nb_exh > 0";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
    
    
    // Actes GHS
    
    $sqlcmd = "INSERT INTO temp.p_rsf_detail(  
                finess, no_rss, nature, mt, dmt, date_debut, date_fin, nombre,   
                coefficient, prix_unitaire, base_remboursement, taux_remboursement,   
                sejour_facture, sejour_remboursable, compteur, ligne_t2a, pec_fj, pec_fj_id,   
                coefficient_mco, sejour_remboursable_2, ghs_id, sejour_rembourse_noemie,   
                nature_noemie, prestation_id, rss_id, type, coefficient_geo, est_ligne_rss, est_ligne_rum, no_rum, unite_medicale_id, base_remboursement_rum)  
            SELECT   
                p_rss.finess, p_rss.no_rss, '' as nature, '' as mt, '' as dmt, p_rss.date_entree as date_debut, p_rss.date_sortie as date_fin,  
                p_rsa.nb_actes_9510,   
                1 as coefficient,   
                CASE  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_1 AND p_rss.date_sortie <= t_ghs.date_fin_public_1 THEN t_ghs.tarif_ghs_public_1  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_2 AND p_rss.date_sortie <= t_ghs.date_fin_public_2 THEN t_ghs.tarif_ghs_public_2  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_3 AND p_rss.date_sortie <= t_ghs.date_fin_public_3 THEN t_ghs.tarif_ghs_public_3  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_4 AND p_rss.date_sortie <= t_ghs.date_fin_public_4 THEN t_ghs.tarif_ghs_public_4  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_5 AND p_rss.date_sortie <= t_ghs.date_fin_public_5 THEN t_ghs.tarif_ghs_public_5  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_6 AND p_rss.date_sortie <= t_ghs.date_fin_public_6 THEN t_ghs.tarif_ghs_public_6  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_7 AND p_rss.date_sortie <= t_ghs.date_fin_public_7 THEN t_ghs.tarif_ghs_public_7  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_8 AND p_rss.date_sortie <= t_ghs.date_fin_public_8 THEN t_ghs.tarif_ghs_public_8  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_9 AND p_rss.date_sortie <= t_ghs.date_fin_public_9 THEN t_ghs.tarif_ghs_public_9  
                ELSE 0::numeric  
                END  
                as prix_unitaire, 0 as base_remboursement, 0 as taux_remboursement,   
                0 as sejour_facture, 0 as sejour_remboursable, '' as compteur, '' as ligne_t2a, '' as pec_fj, 0 as pec_fj_id,   
                1 as coefficient_mco, 0 as sejour_remboursable_2, p_rss.ghs_id as ghs_id, 0 as sejour_rembourse_noemie,   
                '' as nature_noemie, t_prestations.oid as prestation_id, p_rss.oid as rss_id, 'B', 
                1,  '1', '0', 0, 0, 0  
                FROM temp.p_rss, temp.p_rsa, pmsi.t_prestations, pmsi.t_ghs  
                WHERE import_id = $import_id
                AND p_rsa.rss_id = p_rss.oid
                AND t_prestations.code = 'IRRE1'  
                AND p_rss.ghm_id > 0 
                AND t_ghs.code = 9610
                AND p_rss.oid NOT IN (SELECT rss_id FROM temp.p_rsf_detail WHERE prestation_id IN (SELECT oid FROM pmsi.t_prestations WHERE code = 'IRRE1')) 
                AND p_rsa.nb_actes_9510 > 0";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
    
    $sqlcmd = "INSERT INTO temp.p_rsf_detail(  
                finess, no_rss, nature, mt, dmt, date_debut, date_fin, nombre,   
                coefficient, prix_unitaire, base_remboursement, taux_remboursement,   
                sejour_facture, sejour_remboursable, compteur, ligne_t2a, pec_fj, pec_fj_id,   
                coefficient_mco, sejour_remboursable_2, ghs_id, sejour_rembourse_noemie,   
                nature_noemie, prestation_id, rss_id, type, coefficient_geo, est_ligne_rss, est_ligne_rum, no_rum, unite_medicale_id, base_remboursement_rum)  
            SELECT   
                p_rss.finess, p_rss.no_rss, '' as nature, '' as mt, '' as dmt, p_rss.date_entree as date_debut, p_rss.date_sortie as date_fin,  
                p_rsa.nb_actes_9511,   
                1 as coefficient,   
                CASE  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_1 AND p_rss.date_sortie <= t_ghs.date_fin_public_1 THEN t_ghs.tarif_ghs_public_1  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_2 AND p_rss.date_sortie <= t_ghs.date_fin_public_2 THEN t_ghs.tarif_ghs_public_2  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_3 AND p_rss.date_sortie <= t_ghs.date_fin_public_3 THEN t_ghs.tarif_ghs_public_3  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_4 AND p_rss.date_sortie <= t_ghs.date_fin_public_4 THEN t_ghs.tarif_ghs_public_4  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_5 AND p_rss.date_sortie <= t_ghs.date_fin_public_5 THEN t_ghs.tarif_ghs_public_5  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_6 AND p_rss.date_sortie <= t_ghs.date_fin_public_6 THEN t_ghs.tarif_ghs_public_6  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_7 AND p_rss.date_sortie <= t_ghs.date_fin_public_7 THEN t_ghs.tarif_ghs_public_7  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_8 AND p_rss.date_sortie <= t_ghs.date_fin_public_8 THEN t_ghs.tarif_ghs_public_8  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_9 AND p_rss.date_sortie <= t_ghs.date_fin_public_9 THEN t_ghs.tarif_ghs_public_9  
                ELSE 0::numeric  
                END  
                as prix_unitaire, 0 as base_remboursement, 0 as taux_remboursement,   
                0 as sejour_facture, 0 as sejour_remboursable, '' as compteur, '' as ligne_t2a, '' as pec_fj, 0 as pec_fj_id,   
                1 as coefficient_mco, 0 as sejour_remboursable_2, p_rss.ghs_id as ghs_id, 0 as sejour_rembourse_noemie,   
                '' as nature_noemie, t_prestations.oid as prestation_id, p_rss.oid as rss_id, 'B', 
                1,  '1', '0', 0, 0, 0  
                FROM temp.p_rss, temp.p_rsa, pmsi.t_prestations, pmsi.t_ghs  
                WHERE import_id = $import_id
                AND p_rsa.rss_id = p_rss.oid
                AND t_prestations.code = 'IRRE2'  
                AND p_rss.ghm_id > 0 
                AND t_ghs.code = 9611
                AND p_rss.oid NOT IN (SELECT rss_id FROM temp.p_rsf_detail WHERE prestation_id IN (SELECT oid FROM pmsi.t_prestations WHERE code = 'IRRE2')) 
                AND p_rsa.nb_actes_9511 > 0";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
    
    $sqlcmd = "INSERT INTO temp.p_rsf_detail(  
                finess, no_rss, nature, mt, dmt, date_debut, date_fin, nombre,   
                coefficient, prix_unitaire, base_remboursement, taux_remboursement,   
                sejour_facture, sejour_remboursable, compteur, ligne_t2a, pec_fj, pec_fj_id,   
                coefficient_mco, sejour_remboursable_2, ghs_id, sejour_rembourse_noemie,   
                nature_noemie, prestation_id, rss_id, type, coefficient_geo, est_ligne_rss, est_ligne_rum, no_rum, unite_medicale_id, base_remboursement_rum)  
            SELECT   
                p_rss.finess, p_rss.no_rss, '' as nature, '' as mt, '' as dmt, p_rss.date_entree as date_debut, p_rss.date_sortie as date_fin,  
                p_rsa.nb_actes_9512,   
                1 as coefficient,   
                CASE  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_1 AND p_rss.date_sortie <= t_ghs.date_fin_public_1 THEN t_ghs.tarif_ghs_public_1  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_2 AND p_rss.date_sortie <= t_ghs.date_fin_public_2 THEN t_ghs.tarif_ghs_public_2  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_3 AND p_rss.date_sortie <= t_ghs.date_fin_public_3 THEN t_ghs.tarif_ghs_public_3  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_4 AND p_rss.date_sortie <= t_ghs.date_fin_public_4 THEN t_ghs.tarif_ghs_public_4  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_5 AND p_rss.date_sortie <= t_ghs.date_fin_public_5 THEN t_ghs.tarif_ghs_public_5  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_6 AND p_rss.date_sortie <= t_ghs.date_fin_public_6 THEN t_ghs.tarif_ghs_public_6  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_7 AND p_rss.date_sortie <= t_ghs.date_fin_public_7 THEN t_ghs.tarif_ghs_public_7  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_8 AND p_rss.date_sortie <= t_ghs.date_fin_public_8 THEN t_ghs.tarif_ghs_public_8  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_9 AND p_rss.date_sortie <= t_ghs.date_fin_public_9 THEN t_ghs.tarif_ghs_public_9  
                ELSE 0::numeric  
                END  
                as prix_unitaire, 0 as base_remboursement, 0 as taux_remboursement,   
                0 as sejour_facture, 0 as sejour_remboursable, '' as compteur, '' as ligne_t2a, '' as pec_fj, 0 as pec_fj_id,   
                1 as coefficient_mco, 0 as sejour_remboursable_2, p_rss.ghs_id as ghs_id, 0 as sejour_rembourse_noemie,   
                '' as nature_noemie, t_prestations.oid as prestation_id, p_rss.oid as rss_id, 'B', 
                1,  '1', '0', 0, 0, 0  
                FROM temp.p_rss, temp.p_rsa, pmsi.t_prestations, pmsi.t_ghs  
                WHERE import_id = $import_id
                AND p_rsa.rss_id = p_rss.oid
                AND t_prestations.code = 'IRRE3'  
                AND p_rss.ghm_id > 0 
                AND t_ghs.code = 9612
                AND p_rss.oid NOT IN (SELECT rss_id FROM temp.p_rsf_detail WHERE prestation_id IN (SELECT oid FROM pmsi.t_prestations WHERE code = 'IRRE3')) 
                AND p_rsa.nb_actes_9512 > 0";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
    
    $sqlcmd = "INSERT INTO temp.p_rsf_detail(  
                finess, no_rss, nature, mt, dmt, date_debut, date_fin, nombre,   
                coefficient, prix_unitaire, base_remboursement, taux_remboursement,   
                sejour_facture, sejour_remboursable, compteur, ligne_t2a, pec_fj, pec_fj_id,   
                coefficient_mco, sejour_remboursable_2, ghs_id, sejour_rembourse_noemie,   
                nature_noemie, prestation_id, rss_id, type, coefficient_geo, est_ligne_rss, est_ligne_rum, no_rum, unite_medicale_id, base_remboursement_rum)  
            SELECT   
                p_rss.finess, p_rss.no_rss, '' as nature, '' as mt, '' as dmt, p_rss.date_entree as date_debut, p_rss.date_sortie as date_fin,  
                p_rsa.nb_actes_9515,   
                1 as coefficient,   
                CASE  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_1 AND p_rss.date_sortie <= t_ghs.date_fin_public_1 THEN t_ghs.tarif_ghs_public_1  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_2 AND p_rss.date_sortie <= t_ghs.date_fin_public_2 THEN t_ghs.tarif_ghs_public_2  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_3 AND p_rss.date_sortie <= t_ghs.date_fin_public_3 THEN t_ghs.tarif_ghs_public_3  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_4 AND p_rss.date_sortie <= t_ghs.date_fin_public_4 THEN t_ghs.tarif_ghs_public_4  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_5 AND p_rss.date_sortie <= t_ghs.date_fin_public_5 THEN t_ghs.tarif_ghs_public_5  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_6 AND p_rss.date_sortie <= t_ghs.date_fin_public_6 THEN t_ghs.tarif_ghs_public_6  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_7 AND p_rss.date_sortie <= t_ghs.date_fin_public_7 THEN t_ghs.tarif_ghs_public_7  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_8 AND p_rss.date_sortie <= t_ghs.date_fin_public_8 THEN t_ghs.tarif_ghs_public_8  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_9 AND p_rss.date_sortie <= t_ghs.date_fin_public_9 THEN t_ghs.tarif_ghs_public_9  
                ELSE 0::numeric  
                END  
                as prix_unitaire, 0 as base_remboursement, 0 as taux_remboursement,   
                0 as sejour_facture, 0 as sejour_remboursable, '' as compteur, '' as ligne_t2a, '' as pec_fj, 0 as pec_fj_id,   
                1 as coefficient_mco, 0 as sejour_remboursable_2, p_rss.ghs_id as ghs_id, 0 as sejour_rembourse_noemie,   
                '' as nature_noemie, t_prestations.oid as prestation_id, p_rss.oid as rss_id, 'B', 
                1,  '1', '0', 0, 0, 0  
                FROM temp.p_rss, temp.p_rsa, pmsi.t_prestations, pmsi.t_ghs  
                WHERE import_id = $import_id
                AND p_rsa.rss_id = p_rss.oid
                AND t_prestations.code = 'IRRE4'  
                AND p_rss.ghm_id > 0 
                AND t_ghs.code = 9619
                AND p_rss.oid NOT IN (SELECT rss_id FROM temp.p_rsf_detail WHERE prestation_id IN (SELECT oid FROM pmsi.t_prestations WHERE code = 'IRRE4')) 
                AND p_rsa.nb_actes_9515 > 0";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
    
    $sqlcmd = "INSERT INTO temp.p_rsf_detail(  
                finess, no_rss, nature, mt, dmt, date_debut, date_fin, nombre,   
                coefficient, prix_unitaire, base_remboursement, taux_remboursement,   
                sejour_facture, sejour_remboursable, compteur, ligne_t2a, pec_fj, pec_fj_id,   
                coefficient_mco, sejour_remboursable_2, ghs_id, sejour_rembourse_noemie,   
                nature_noemie, prestation_id, rss_id, type, coefficient_geo, est_ligne_rss, est_ligne_rum, no_rum, unite_medicale_id, base_remboursement_rum)  
            SELECT   
                p_rss.finess, p_rss.no_rss, '' as nature, '' as mt, '' as dmt, p_rss.date_entree as date_debut, p_rss.date_sortie as date_fin,  
                p_rsa.nb_actes_9524,   
                1 as coefficient,   
                CASE  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_1 AND p_rss.date_sortie <= t_ghs.date_fin_public_1 THEN t_ghs.tarif_ghs_public_1  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_2 AND p_rss.date_sortie <= t_ghs.date_fin_public_2 THEN t_ghs.tarif_ghs_public_2  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_3 AND p_rss.date_sortie <= t_ghs.date_fin_public_3 THEN t_ghs.tarif_ghs_public_3  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_4 AND p_rss.date_sortie <= t_ghs.date_fin_public_4 THEN t_ghs.tarif_ghs_public_4  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_5 AND p_rss.date_sortie <= t_ghs.date_fin_public_5 THEN t_ghs.tarif_ghs_public_5  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_6 AND p_rss.date_sortie <= t_ghs.date_fin_public_6 THEN t_ghs.tarif_ghs_public_6  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_7 AND p_rss.date_sortie <= t_ghs.date_fin_public_7 THEN t_ghs.tarif_ghs_public_7  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_8 AND p_rss.date_sortie <= t_ghs.date_fin_public_8 THEN t_ghs.tarif_ghs_public_8  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_9 AND p_rss.date_sortie <= t_ghs.date_fin_public_9 THEN t_ghs.tarif_ghs_public_9  
                ELSE 0::numeric  
                END  
                as prix_unitaire, 0 as base_remboursement, 0 as taux_remboursement,   
                0 as sejour_facture, 0 as sejour_remboursable, '' as compteur, '' as ligne_t2a, '' as pec_fj, 0 as pec_fj_id,   
                1 as coefficient_mco, 0 as sejour_remboursable_2, p_rss.ghs_id as ghs_id, 0 as sejour_rembourse_noemie,   
                '' as nature_noemie, t_prestations.oid as prestation_id, p_rss.oid as rss_id, 'B', 
                1,  '1', '0', 0, 0, 0  
                FROM temp.p_rss, temp.p_rsa, pmsi.t_prestations, pmsi.t_ghs  
                WHERE import_id = $import_id
                AND p_rsa.rss_id = p_rss.oid
                AND t_prestations.code = 'IRRE5'  
                AND p_rss.ghm_id > 0 
                AND t_ghs.code = 9620
                AND p_rss.oid NOT IN (SELECT rss_id FROM temp.p_rsf_detail WHERE prestation_id IN (SELECT oid FROM pmsi.t_prestations WHERE code = 'IRRE5')) 
                AND p_rsa.nb_actes_9524 > 0";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
    
    
    $sqlcmd = "INSERT INTO temp.p_rsf_detail(  
                finess, no_rss, nature, mt, dmt, date_debut, date_fin, nombre,   
                coefficient, prix_unitaire, base_remboursement, taux_remboursement,   
                sejour_facture, sejour_remboursable, compteur, ligne_t2a, pec_fj, pec_fj_id,   
                coefficient_mco, sejour_remboursable_2, ghs_id, sejour_rembourse_noemie,   
                nature_noemie, prestation_id, rss_id, type, coefficient_geo, est_ligne_rss, est_ligne_rum, no_rum, unite_medicale_id, base_remboursement_rum)  
            SELECT   
                p_rss.finess, p_rss.no_rss, '' as nature, '' as mt, '' as dmt, p_rss.date_entree as date_debut, p_rss.date_sortie as date_fin,  
                p_rsa.nb_sup_apherese,   
                1 as coefficient,   
                CASE  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_1 AND p_rss.date_sortie <= t_ghs.date_fin_public_1 THEN t_ghs.tarif_ghs_public_1  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_2 AND p_rss.date_sortie <= t_ghs.date_fin_public_2 THEN t_ghs.tarif_ghs_public_2  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_3 AND p_rss.date_sortie <= t_ghs.date_fin_public_3 THEN t_ghs.tarif_ghs_public_3  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_4 AND p_rss.date_sortie <= t_ghs.date_fin_public_4 THEN t_ghs.tarif_ghs_public_4  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_5 AND p_rss.date_sortie <= t_ghs.date_fin_public_5 THEN t_ghs.tarif_ghs_public_5  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_6 AND p_rss.date_sortie <= t_ghs.date_fin_public_6 THEN t_ghs.tarif_ghs_public_6  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_7 AND p_rss.date_sortie <= t_ghs.date_fin_public_7 THEN t_ghs.tarif_ghs_public_7  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_8 AND p_rss.date_sortie <= t_ghs.date_fin_public_8 THEN t_ghs.tarif_ghs_public_8  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_9 AND p_rss.date_sortie <= t_ghs.date_fin_public_9 THEN t_ghs.tarif_ghs_public_9  
                ELSE 0::numeric  
                END  
                as prix_unitaire, 0 as base_remboursement, 0 as taux_remboursement,   
                0 as sejour_facture, 0 as sejour_remboursable, '' as compteur, '' as ligne_t2a, '' as pec_fj, 0 as pec_fj_id,   
                1 as coefficient_mco, 0 as sejour_remboursable_2, p_rss.ghs_id as ghs_id, 0 as sejour_rembourse_noemie,   
                '' as nature_noemie, t_prestations.oid as prestation_id, p_rss.oid as rss_id, 'B', 
                1,  '1', '0', 0, 0, 0  
                FROM temp.p_rss, temp.p_rsa, pmsi.t_prestations, pmsi.t_ghs  
                WHERE import_id = $import_id
                AND p_rsa.rss_id = p_rss.oid
                AND t_prestations.code = 'APHE'  
                AND p_rss.ghm_id > 0 
                AND t_ghs.code = 9615
                AND p_rss.oid NOT IN (SELECT rss_id FROM temp.p_rsf_detail WHERE prestation_id IN (SELECT oid FROM pmsi.t_prestations WHERE code = 'APHE')) 
                AND p_rsa.nb_sup_apherese > 0";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
    
    $sqlcmd = "INSERT INTO temp.p_rsf_detail(  
                finess, no_rss, nature, mt, dmt, date_debut, date_fin, nombre,   
                coefficient, prix_unitaire, base_remboursement, taux_remboursement,   
                sejour_facture, sejour_remboursable, compteur, ligne_t2a, pec_fj, pec_fj_id,   
                coefficient_mco, sejour_remboursable_2, ghs_id, sejour_rembourse_noemie,   
                nature_noemie, prestation_id, rss_id, type, coefficient_geo, est_ligne_rss, est_ligne_rum, no_rum, unite_medicale_id, base_remboursement_rum)  
            SELECT   
                p_rss.finess, p_rss.no_rss, '' as nature, '' as mt, '' as dmt, p_rss.date_entree as date_debut, p_rss.date_sortie as date_fin,  
                p_rsa.nb_actes_9622,   
                1 as coefficient,   
                CASE  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_1 AND p_rss.date_sortie <= t_ghs.date_fin_public_1 THEN t_ghs.tarif_ghs_public_1  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_2 AND p_rss.date_sortie <= t_ghs.date_fin_public_2 THEN t_ghs.tarif_ghs_public_2  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_3 AND p_rss.date_sortie <= t_ghs.date_fin_public_3 THEN t_ghs.tarif_ghs_public_3  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_4 AND p_rss.date_sortie <= t_ghs.date_fin_public_4 THEN t_ghs.tarif_ghs_public_4  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_5 AND p_rss.date_sortie <= t_ghs.date_fin_public_5 THEN t_ghs.tarif_ghs_public_5  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_6 AND p_rss.date_sortie <= t_ghs.date_fin_public_6 THEN t_ghs.tarif_ghs_public_6  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_7 AND p_rss.date_sortie <= t_ghs.date_fin_public_7 THEN t_ghs.tarif_ghs_public_7  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_8 AND p_rss.date_sortie <= t_ghs.date_fin_public_8 THEN t_ghs.tarif_ghs_public_8  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_9 AND p_rss.date_sortie <= t_ghs.date_fin_public_9 THEN t_ghs.tarif_ghs_public_9  
                ELSE 0::numeric  
                END  
                as prix_unitaire, 0 as base_remboursement, 0 as taux_remboursement,   
                0 as sejour_facture, 0 as sejour_remboursable, '' as compteur, '' as ligne_t2a, '' as pec_fj, 0 as pec_fj_id,   
                1 as coefficient_mco, 0 as sejour_remboursable_2, p_rss.ghs_id as ghs_id, 0 as sejour_rembourse_noemie,   
                '' as nature_noemie, t_prestations.oid as prestation_id, p_rss.oid as rss_id, 'B', 
                1,  '1', '0', 0, 0, 0  
                FROM temp.p_rss, temp.p_rsa, pmsi.t_prestations, pmsi.t_ghs  
                WHERE import_id = $import_id
                AND p_rsa.rss_id = p_rss.oid
                AND t_prestations.code = 'IRRE7'  
                AND p_rss.ghm_id > 0 
                AND t_ghs.code = 9622
                AND p_rss.oid NOT IN (SELECT rss_id FROM temp.p_rsf_detail WHERE prestation_id IN (SELECT oid FROM pmsi.t_prestations WHERE code = 'IRRE7')) 
                AND p_rsa.nb_actes_9622 > 0";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
    
    $sqlcmd = "INSERT INTO temp.p_rsf_detail(  
                finess, no_rss, nature, mt, dmt, date_debut, date_fin, nombre,   
                coefficient, prix_unitaire, base_remboursement, taux_remboursement,   
                sejour_facture, sejour_remboursable, compteur, ligne_t2a, pec_fj, pec_fj_id,   
                coefficient_mco, sejour_remboursable_2, ghs_id, sejour_rembourse_noemie,   
                nature_noemie, prestation_id, rss_id, type, coefficient_geo, est_ligne_rss, est_ligne_rum, no_rum, unite_medicale_id, base_remboursement_rum)  
            SELECT   
                p_rss.finess, p_rss.no_rss, '' as nature, '' as mt, '' as dmt, p_rss.date_entree as date_debut, p_rss.date_sortie as date_fin,  
                p_rsa.nb_actes_9621,   
                1 as coefficient,   
                CASE  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_1 AND p_rss.date_sortie <= t_ghs.date_fin_public_1 THEN t_ghs.tarif_ghs_public_1  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_2 AND p_rss.date_sortie <= t_ghs.date_fin_public_2 THEN t_ghs.tarif_ghs_public_2  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_3 AND p_rss.date_sortie <= t_ghs.date_fin_public_3 THEN t_ghs.tarif_ghs_public_3  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_4 AND p_rss.date_sortie <= t_ghs.date_fin_public_4 THEN t_ghs.tarif_ghs_public_4  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_5 AND p_rss.date_sortie <= t_ghs.date_fin_public_5 THEN t_ghs.tarif_ghs_public_5  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_6 AND p_rss.date_sortie <= t_ghs.date_fin_public_6 THEN t_ghs.tarif_ghs_public_6  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_7 AND p_rss.date_sortie <= t_ghs.date_fin_public_7 THEN t_ghs.tarif_ghs_public_7  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_8 AND p_rss.date_sortie <= t_ghs.date_fin_public_8 THEN t_ghs.tarif_ghs_public_8  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_9 AND p_rss.date_sortie <= t_ghs.date_fin_public_9 THEN t_ghs.tarif_ghs_public_9  
                ELSE 0::numeric  
                END  
                as prix_unitaire, 0 as base_remboursement, 0 as taux_remboursement,   
                0 as sejour_facture, 0 as sejour_remboursable, '' as compteur, '' as ligne_t2a, '' as pec_fj, 0 as pec_fj_id,   
                1 as coefficient_mco, 0 as sejour_remboursable_2, p_rss.ghs_id as ghs_id, 0 as sejour_rembourse_noemie,   
                '' as nature_noemie, t_prestations.oid as prestation_id, p_rss.oid as rss_id, 'B', 
                1,  '1', '0', 0, 0, 0  
                FROM temp.p_rss, temp.p_rsa, pmsi.t_prestations, pmsi.t_ghs  
                WHERE import_id = $import_id
                AND p_rsa.rss_id = p_rss.oid
                AND t_prestations.code = 'IRRE6'  
                AND p_rss.ghm_id > 0 
                AND t_ghs.code = 9621
                AND p_rss.oid NOT IN (SELECT rss_id FROM temp.p_rsf_detail WHERE prestation_id IN (SELECT oid FROM pmsi.t_prestations WHERE code = 'IRRE6')) 
                AND p_rsa.nb_actes_9621 > 0";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
    
    $sqlcmd = "INSERT INTO temp.p_rsf_detail(  
                finess, no_rss, nature, mt, dmt, date_debut, date_fin, nombre,   
                coefficient, prix_unitaire, base_remboursement, taux_remboursement,   
                sejour_facture, sejour_remboursable, compteur, ligne_t2a, pec_fj, pec_fj_id,   
                coefficient_mco, sejour_remboursable_2, ghs_id, sejour_rembourse_noemie,   
                nature_noemie, prestation_id, rss_id, type, coefficient_geo, est_ligne_rss, est_ligne_rum, no_rum, unite_medicale_id, base_remboursement_rum)  
            SELECT   
                p_rss.finess, p_rss.no_rss, '' as nature, '' as mt, '' as dmt, p_rss.date_entree as date_debut, p_rss.date_sortie as date_fin,  
                p_rsa.nb_actes_6523,   
                1 as coefficient,   
                CASE  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_1 AND p_rss.date_sortie <= t_ghs.date_fin_public_1 THEN t_ghs.tarif_ghs_public_1  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_2 AND p_rss.date_sortie <= t_ghs.date_fin_public_2 THEN t_ghs.tarif_ghs_public_2  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_3 AND p_rss.date_sortie <= t_ghs.date_fin_public_3 THEN t_ghs.tarif_ghs_public_3  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_4 AND p_rss.date_sortie <= t_ghs.date_fin_public_4 THEN t_ghs.tarif_ghs_public_4  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_5 AND p_rss.date_sortie <= t_ghs.date_fin_public_5 THEN t_ghs.tarif_ghs_public_5  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_6 AND p_rss.date_sortie <= t_ghs.date_fin_public_6 THEN t_ghs.tarif_ghs_public_6  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_7 AND p_rss.date_sortie <= t_ghs.date_fin_public_7 THEN t_ghs.tarif_ghs_public_7  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_8 AND p_rss.date_sortie <= t_ghs.date_fin_public_8 THEN t_ghs.tarif_ghs_public_8  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_9 AND p_rss.date_sortie <= t_ghs.date_fin_public_9 THEN t_ghs.tarif_ghs_public_9  
                ELSE 0::numeric  
                END  
                as prix_unitaire, 0 as base_remboursement, 0 as taux_remboursement,   
                0 as sejour_facture, 0 as sejour_remboursable, '' as compteur, '' as ligne_t2a, '' as pec_fj, 0 as pec_fj_id,   
                1 as coefficient_mco, 0 as sejour_remboursable_2, p_rss.ghs_id as ghs_id, 0 as sejour_rembourse_noemie,   
                '' as nature_noemie, t_prestations.oid as prestation_id, p_rss.oid as rss_id, 'B', 
                1,  '1', '0', 0, 0, 0  
                FROM temp.p_rss, temp.p_rsa, pmsi.t_prestations, pmsi.t_ghs  
                WHERE import_id = $import_id
                AND p_rsa.rss_id = p_rss.oid
                AND t_prestations.code = 'IRRE0'  
                AND p_rss.ghm_id > 0 
                AND t_ghs.code = 6523
                AND p_rss.oid NOT IN (SELECT rss_id FROM temp.p_rsf_detail WHERE prestation_id IN (SELECT oid FROM pmsi.t_prestations WHERE code = 'IRRE0')) 
                AND p_rsa.nb_actes_6523 > 0";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
        
    $supp_rdth = array(
        "= 9610" => "IRRE1",
        "= 9611" => "IRRE2",
        "= 9612" => "IRRE3",
        "= 9619" => "IRRE4",
        "= 9620" => "IRRE5",
        "= 9621" => "IRRE6",
        "= 9622" => "IRRE7",
        "= 9624" => "IRRE8",
        "= 9625" => "IRRE9",
        "= 9631" => "IRRE10",
        "= 9632" => "IRRE11",
        "= 9633" => "IRRE12",
        "= 9615" => "APHE",
        "NOT IN (9610,9611,9612,9619,9620,9621,9622,9624,9625,9631,9632,9633,9615)" => "IRRE0"
    );
    foreach($supp_rdth as $rdth_ghs_id => $rdth_prestation_code){
        $sqlcmd = "INSERT INTO temp.p_rsf_detail(  
                finess, no_rss, nature, mt, dmt, date_debut, date_fin, nombre,   
                coefficient, prix_unitaire, base_remboursement, taux_remboursement,   
                sejour_facture, sejour_remboursable, compteur, ligne_t2a, pec_fj, pec_fj_id,   
                coefficient_mco, sejour_remboursable_2, ghs_id, sejour_rembourse_noemie,   
                nature_noemie, prestation_id, rss_id, type, coefficient_geo, est_ligne_rss, est_ligne_rum, no_rum, unite_medicale_id, base_remboursement_rum)  
            SELECT   
                finess, p_rss.no_rss, '' as nature, '' as mt, '' as dmt, date_entree as date_debut, date_sortie as date_fin,  
                p_rsa_rdth.nb_supplements,   
                1 as coefficient,   
                CASE  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_1 AND p_rss.date_sortie <= t_ghs.date_fin_public_1 THEN t_ghs.tarif_ghs_public_1  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_2 AND p_rss.date_sortie <= t_ghs.date_fin_public_2 THEN t_ghs.tarif_ghs_public_2  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_3 AND p_rss.date_sortie <= t_ghs.date_fin_public_3 THEN t_ghs.tarif_ghs_public_3  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_4 AND p_rss.date_sortie <= t_ghs.date_fin_public_4 THEN t_ghs.tarif_ghs_public_4  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_5 AND p_rss.date_sortie <= t_ghs.date_fin_public_5 THEN t_ghs.tarif_ghs_public_5  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_6 AND p_rss.date_sortie <= t_ghs.date_fin_public_6 THEN t_ghs.tarif_ghs_public_6  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_7 AND p_rss.date_sortie <= t_ghs.date_fin_public_7 THEN t_ghs.tarif_ghs_public_7  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_8 AND p_rss.date_sortie <= t_ghs.date_fin_public_8 THEN t_ghs.tarif_ghs_public_8  
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_9 AND p_rss.date_sortie <= t_ghs.date_fin_public_9 THEN t_ghs.tarif_ghs_public_9  
                ELSE 0::numeric  
                END  
                as prix_unitaire, 0 as base_remboursement, 0 as taux_remboursement,   
                0 as sejour_facture, 0 as sejour_remboursable, '' as compteur, '' as ligne_t2a, '' as pec_fj, 0 as pec_fj_id,   
                1 as coefficient_mco, 0 as sejour_remboursable_2, p_rss.ghs_id as ghs_id, 0 as sejour_rembourse_noemie,   
                '' as nature_noemie, t_prestations.oid as prestation_id, p_rss.oid as rss_id, 'B', 
                1,  '1', '0', 0, 0, 0  
            FROM temp.p_rss
            JOIN temp.p_rsa_rdth ON p_rsa_rdth.rss_id = p_rss.oid
            JOIN pmsi.t_ghs ON t_ghs.oid = p_rsa_rdth.ghs_id
            JOIN pmsi.t_prestations ON t_prestations.code = '$rdth_prestation_code'
            WHERE 
                import_id = $import_id
                AND p_rss.ghm_id > 0 
                AND p_rsa_rdth.nb_supplements > 0
                AND t_ghs.code $rdth_ghs_id
                AND p_rss.oid NOT IN (
                    SELECT rss_id 
                    FROM temp.p_rsf_detail 
                    WHERE prestation_id IN (SELECT oid FROM pmsi.t_prestations WHERE code = '$rdth_prestation_code')
                )
        ";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
        commit_trans();
    }
    
    // Prévalorisation GHS/EXH
    $sqlcmd = "UPDATE temp.p_rsf_detail 
        SET sejour_rembourse_noemie = prix_unitaire * nombre  ,
            update_rules = array_append(update_rules, 22)
        FROM temp.p_rss, pmsi.t_prestations 
        WHERE import_id = $import_id 
            AND p_rsf_detail.rss_id = p_rss.oid AND  p_rsf_detail.type = 'B' AND p_rsf_detail.est_ligne_rss = '1'
            AND p_rsf_detail.prestation_id = t_prestations.oid 
            AND t_prestations.code IN ('GHS', 'EXH', 'IRRE0', 'IRRE1', 'IRRE2', 'IRRE3', 'IRRE4',
                'IRRE5', 'IRRE6', 'IRRE7', 'IRRE8', 'IRRE9', 'IRRE10', 'IRRE11', 'IRRE12', 'APHE') 
    ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();

    // EXB avec RSA
    
    // EXB sans transfert avec forfait
    $sqlcmd = "UPDATE temp.p_rsf_detail 
                SET sejour_rembourse_noemie =  
                sejour_rembourse_noemie 
                - 
                CASE 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_1 AND p_rss.date_sortie <= t_ghs.date_fin_public_1 THEN t_ghs.forfait_exb_public_1 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_2 AND p_rss.date_sortie <= t_ghs.date_fin_public_2 THEN t_ghs.forfait_exb_public_2 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_3 AND p_rss.date_sortie <= t_ghs.date_fin_public_3 THEN t_ghs.forfait_exb_public_3 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_4 AND p_rss.date_sortie <= t_ghs.date_fin_public_4 THEN t_ghs.forfait_exb_public_4 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_5 AND p_rss.date_sortie <= t_ghs.date_fin_public_5 THEN t_ghs.forfait_exb_public_5 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_6 AND p_rss.date_sortie <= t_ghs.date_fin_public_6 THEN t_ghs.forfait_exb_public_6 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_7 AND p_rss.date_sortie <= t_ghs.date_fin_public_7 THEN t_ghs.forfait_exb_public_7 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_8 AND p_rss.date_sortie <= t_ghs.date_fin_public_8 THEN t_ghs.forfait_exb_public_8 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_9 AND p_rss.date_sortie <= t_ghs.date_fin_public_9 THEN t_ghs.forfait_exb_public_9 
                ELSE 0::numeric 
                END,
                update_rules = array_append(update_rules, 26)
                FROM 
                temp.p_rss, temp.p_rsa, pmsi.t_prestations, pmsi.t_ghs 
                WHERE import_id = $import_id 
                AND p_rss.oid = p_rsa.rss_id
                AND p_rsf_detail.rss_id = p_rss.oid 
                AND p_rsf_detail.type = 'B'  AND p_rsf_detail.est_ligne_rss = '1'
                AND p_rsf_detail.prestation_id = t_prestations.oid 
                AND t_prestations.code = 'GHS' 
                AND p_rsf_detail.ghs_id = t_ghs.oid 
                AND p_rss.duree_sejour >= 0 
                AND p_rsa.nb_exb > 0
                AND CASE 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_1 AND p_rss.date_sortie <= t_ghs.date_fin_public_1 THEN t_ghs.forfait_exb_public_1 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_2 AND p_rss.date_sortie <= t_ghs.date_fin_public_2 THEN t_ghs.forfait_exb_public_2 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_3 AND p_rss.date_sortie <= t_ghs.date_fin_public_3 THEN t_ghs.forfait_exb_public_3 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_4 AND p_rss.date_sortie <= t_ghs.date_fin_public_4 THEN t_ghs.forfait_exb_public_4 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_5 AND p_rss.date_sortie <= t_ghs.date_fin_public_5 THEN t_ghs.forfait_exb_public_5 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_6 AND p_rss.date_sortie <= t_ghs.date_fin_public_6 THEN t_ghs.forfait_exb_public_6 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_7 AND p_rss.date_sortie <= t_ghs.date_fin_public_7 THEN t_ghs.forfait_exb_public_7 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_8 AND p_rss.date_sortie <= t_ghs.date_fin_public_8 THEN t_ghs.forfait_exb_public_8 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_9 AND p_rss.date_sortie <= t_ghs.date_fin_public_9 THEN t_ghs.forfait_exb_public_9 
                ELSE 0::numeric 
                END > 0 ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();





    // EXB Sans transfert avec tarif  
    $sqlcmd = "UPDATE temp.p_rsf_detail 
                SET sejour_rembourse_noemie =  
                sejour_rembourse_noemie 
                - 
                round( 
                p_rsa.nb_exb / 10.00
                * 
                CASE 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_1 AND p_rss.date_sortie <= t_ghs.date_fin_public_1 THEN t_ghs.tarif_exb_public_1 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_2 AND p_rss.date_sortie <= t_ghs.date_fin_public_2 THEN t_ghs.tarif_exb_public_2 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_3 AND p_rss.date_sortie <= t_ghs.date_fin_public_3 THEN t_ghs.tarif_exb_public_3 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_4 AND p_rss.date_sortie <= t_ghs.date_fin_public_4 THEN t_ghs.tarif_exb_public_4 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_5 AND p_rss.date_sortie <= t_ghs.date_fin_public_5 THEN t_ghs.tarif_exb_public_5 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_6 AND p_rss.date_sortie <= t_ghs.date_fin_public_6 THEN t_ghs.tarif_exb_public_6 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_7 AND p_rss.date_sortie <= t_ghs.date_fin_public_7 THEN t_ghs.tarif_exb_public_7 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_8 AND p_rss.date_sortie <= t_ghs.date_fin_public_8 THEN t_ghs.tarif_exb_public_8 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_9 AND p_rss.date_sortie <= t_ghs.date_fin_public_9 THEN t_ghs.tarif_exb_public_9 
                ELSE 0::numeric 
                END 
                , 2),
                update_rules = array_append(update_rules, 27)
                FROM 
                temp.p_rss, temp.p_rsa, pmsi.t_prestations, pmsi.t_ghs 
                WHERE import_id = $import_id
                AND p_rss.oid = p_rsa.rss_id
                AND p_rsf_detail.rss_id = p_rss.oid AND  p_rsf_detail.type = 'B'  AND p_rsf_detail.est_ligne_rss = '1'
                AND p_rsf_detail.prestation_id = t_prestations.oid 
                AND t_prestations.code = 'GHS' 
                AND p_rsf_detail.ghs_id = t_ghs.oid 
                AND p_rss.mode_sortie <> '9' 
                AND p_rsa.nb_exb > 0 
                AND CASE 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_1 AND p_rss.date_sortie <= t_ghs.date_fin_public_1 THEN t_ghs.forfait_exb_public_1 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_2 AND p_rss.date_sortie <= t_ghs.date_fin_public_2 THEN t_ghs.forfait_exb_public_2 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_3 AND p_rss.date_sortie <= t_ghs.date_fin_public_3 THEN t_ghs.forfait_exb_public_3 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_4 AND p_rss.date_sortie <= t_ghs.date_fin_public_4 THEN t_ghs.forfait_exb_public_4 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_5 AND p_rss.date_sortie <= t_ghs.date_fin_public_5 THEN t_ghs.forfait_exb_public_5 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_6 AND p_rss.date_sortie <= t_ghs.date_fin_public_6 THEN t_ghs.forfait_exb_public_6 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_7 AND p_rss.date_sortie <= t_ghs.date_fin_public_7 THEN t_ghs.forfait_exb_public_7 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_8 AND p_rss.date_sortie <= t_ghs.date_fin_public_8 THEN t_ghs.forfait_exb_public_8 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_9 AND p_rss.date_sortie <= t_ghs.date_fin_public_9 THEN t_ghs.forfait_exb_public_9 
                ELSE 0::numeric 
                END = 0 
                AND CASE 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_1 AND p_rss.date_sortie <= t_ghs.date_fin_public_1 THEN t_ghs.tarif_exb_public_1 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_2 AND p_rss.date_sortie <= t_ghs.date_fin_public_2 THEN t_ghs.tarif_exb_public_2 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_3 AND p_rss.date_sortie <= t_ghs.date_fin_public_3 THEN t_ghs.tarif_exb_public_3 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_4 AND p_rss.date_sortie <= t_ghs.date_fin_public_4 THEN t_ghs.tarif_exb_public_4 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_5 AND p_rss.date_sortie <= t_ghs.date_fin_public_5 THEN t_ghs.tarif_exb_public_5 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_6 AND p_rss.date_sortie <= t_ghs.date_fin_public_6 THEN t_ghs.tarif_exb_public_6 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_7 AND p_rss.date_sortie <= t_ghs.date_fin_public_7 THEN t_ghs.tarif_exb_public_7 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_8 AND p_rss.date_sortie <= t_ghs.date_fin_public_8 THEN t_ghs.tarif_exb_public_8 
                WHEN p_rss.date_sortie >= t_ghs.date_debut_public_9 AND p_rss.date_sortie <= t_ghs.date_fin_public_9 THEN t_ghs.tarif_exb_public_9 
                ELSE 0::numeric 
                END > 0 ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
    
    // Réhospitalisations même GHM
    $sqlcmd = "DROP TABLE IF EXISTS w_rehosp;

            CREATE temp TABLE w_rehosp AS

            SELECT p_vidhosp.no_anonyme, p_rss.oid, p_rss.no_rss, p_rss.date_entree, p_rss.date_sortie, p_rss.ghm_id,
                0 AS from_rss_id, '20991231'::date AS from_date_sortie
            FROM temp.p_rss
            JOIN temp.p_vidhosp ON p_vidhosp.rss_id = p_rss.oid AND p_vidhosp.no_anonyme IS NOT NULL AND p_vidhosp.no_anonyme <> ''
            WHERE p_rss.mode_entree = '7'
                AND p_rss.provenance = '1'
                AND p_rss.import_id = $import_id
                AND p_rss.ghm_id <> 0
                AND p_rss.ghm_id not in (SELECT oid FROM pmsi.t_ghm WHERE code like '28%' OR code like '24%' OR texte ilike 'séance%');


            UPDATE w_rehosp 
            SET 
                from_date_sortie = 
                    (SELECT MAX(p_rss_b.date_sortie) 
                    FROM temp.p_rss p_rss_b 
                        JOIN temp.p_vidhosp ON p_vidhosp.rss_id = p_rss_b.oid 
                    WHERE w_rehosp.no_anonyme = p_vidhosp.no_anonyme AND 
                        p_rss_b.import_id = $import_id AND 
                        p_rss_b.ghm_id <> 0 AND 
                        p_rss_b.date_sortie < w_rehosp.date_entree),
                from_rss_id = 
                    (SELECT to_number(substr(MAX(p_rss_b.date_sortie::text || p_rss_b.oid::text), 11, 20),'999999999999') 
                    FROM temp.p_rss p_rss_b
                        JOIN temp.p_vidhosp ON p_vidhosp.rss_id = p_rss_b.oid 
                    WHERE w_rehosp.no_anonyme = p_vidhosp.no_anonyme AND 
                        p_rss_b.import_id = $import_id AND 
                        p_rss_b.ghm_id <> 0 AND 
                        p_rss_b.date_sortie < w_rehosp.date_entree)
            ;

            UPDATE temp.p_rss 
            SET rehosp_meme_ghm = '1'
            FROM w_rehosp, temp.p_rss p_rss_p, temp.p_rsf_detail
            WHERE p_rss_p.oid = from_rss_id
                AND p_rss.oid = w_rehosp.oid
                AND p_rss_p.mode_sortie = '7'
                AND p_rss_p.destination = '1'
                AND p_rss_p.ghm_id = w_rehosp.ghm_id
                AND w_rehosp.date_entree - from_date_sortie BETWEEN 3 AND 10
                AND w_rehosp.oid = p_rsf_detail.rss_id
                AND p_rsf_detail.prestation_id IN (select oid FROM pmsi.t_prestations WHERE code = 'GHS')
                AND p_rsf_detail.type = 'B' AND p_rsf_detail.est_ligne_rss = '1';


            UPDATE temp.p_rsf_detail
            SET sejour_rembourse_noemie = round(sejour_rembourse_noemie / 2,2),
                update_rules = array_append(update_rules, 28)
            FROM temp.p_rss 
            WHERE import_id = $import_id
                AND p_rsf_detail.rss_id = p_rss.oid
                AND p_rsf_detail.prestation_id IN (select oid FROM pmsi.t_prestations WHERE code = 'GHS')
                AND p_rsf_detail.type = 'B' AND p_rsf_detail.est_ligne_rss = '1'
                AND p_rss.rehosp_meme_ghm = '1';";
            
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
    
    // Suppléments 
    logInfoMsg("Génération suppléments");
        
    // Generation supplements avec RSA
    // Depuis 2013 Les forfaits D passent en GHS
    // http://www.atih.sante.fr/sites/default/files/public/content/2435/notice_technique_financement_2014_cim-mf-249-1-2014.pdf
    // 
    $sqlcmd = "INSERT INTO temp.p_rsf_detail(  
                finess, no_rss, nature, mt, dmt, date_debut, date_fin, nombre,   
                coefficient, prix_unitaire, base_remboursement, taux_remboursement,   
                sejour_facture, sejour_remboursable, compteur, ligne_t2a, pec_fj, pec_fj_id,   
                coefficient_mco, sejour_remboursable_2, ghs_id, sejour_rembourse_noemie,   
                nature_noemie, prestation_id, rss_id, type, coefficient_geo, est_ligne_rss, est_ligne_rum, no_rum, unite_medicale_id, base_remboursement_rum)   
                SELECT p_rss.finess, p_rss.no_rss, '', '', '', p_rss.date_entree, p_rss.date_sortie,   
                    subview.nombre,  
                    1,   
                    COALESCE(t_prestation_tarif.tarif,0),
                    0, 100, 0, 0, '', '', '', 0, 0, 0, 0, 0, '', t_prestations.oid, p_rss.oid, 'B', 
                    1,  '1', '0', 0, 0, 0  
                FROM temp.p_rss 
                JOIN (SELECT rss_id, 'SRA' as supplement_code, nb_sup_sra as nombre FROM temp.p_rsa WHERE nb_sup_sra > 0
                    UNION
                    SELECT rss_id, 'REA' as supplement_code, nb_sup_rea as nombre FROM temp.p_rsa WHERE nb_sup_rea > 0
                    UNION
                    SELECT rss_id, 'STF' as supplement_code, nb_sup_stf as nombre FROM temp.p_rsa WHERE nb_sup_stf > 0
                    UNION
                    SELECT rss_id, 'SSC' as supplement_code, nb_sup_ssc as nombre FROM temp.p_rsa WHERE nb_sup_ssc > 0
                    UNION
                    SELECT rss_id, 'SRC' as supplement_code, nb_sup_src as nombre FROM temp.p_rsa WHERE nb_sup_src > 0
                    UNION
                    SELECT rss_id, 'NN1' as supplement_code, nb_sup_nn1 as nombre FROM temp.p_rsa WHERE nb_sup_nn1 > 0
                    UNION
                    SELECT rss_id, 'NN2' as supplement_code, nb_sup_nn2 as nombre FROM temp.p_rsa WHERE nb_sup_nn2 > 0
                    UNION
                    SELECT rss_id, 'NN3' as supplement_code, nb_sup_nn3 as nombre FROM temp.p_rsa WHERE nb_sup_nn3 > 0
                    UNION
                    SELECT rss_id, 'D09' as supplement_code, nb_sup_dialyse_1 as nombre FROM temp.p_rsa WHERE nb_sup_dialyse_1 > 0
                    UNION
                    SELECT rss_id, 'D18' as supplement_code, nb_sup_dialyse_2 as nombre FROM temp.p_rsa WHERE nb_sup_dialyse_2 > 0
                    UNION
                    SELECT rss_id, 'D19' as supplement_code, nb_sup_dialyse_3 as nombre FROM temp.p_rsa WHERE nb_sup_dialyse_3 > 0
                    UNION
                    SELECT rss_id, 'D17' as supplement_code, nb_sup_dialyse_4 as nombre FROM temp.p_rsa WHERE nb_sup_dialyse_4 > 0
                    UNION
                    SELECT rss_id, 'OHB' as supplement_code, nb_sup_hyperbare as nombre FROM temp.p_rsa WHERE nb_sup_hyperbare > 0
                    UNION
                    SELECT rss_id, 'ANT' as supplement_code, nb_sup_ant as nombre FROM temp.p_rsa WHERE nb_sup_ant > 0
                    UNION
                    SELECT rss_id, 'RAP' as supplement_code, nb_sup_rap as nombre FROM temp.p_rsa WHERE nb_sup_rap > 0
                    UNION
                    SELECT rss_id, 'SDC' as supplement_code, nb_sup_sdc as nombre FROM temp.p_rsa WHERE nb_sup_sdc > 0
                    UNION
                    SELECT rss_id, supplement_code, nombre
                    FROM (
                        SELECT
                            base.cti_to_number(substr(data,27,10)) AS no_rsa, 
                            substr(data,37,3) AS supplement_code,
                            base.cti_to_number(substr(data,40,10)) as nombre
                        FROM w_out_diap
                        ) subview
                        JOIN temp.p_rsa ON subview.no_rsa = p_rsa.no_rsa
                    UNION
                    SELECT rss_id, supplement_code, nombre
                    FROM (
                        SELECT
                            base.cti_to_number(substr(data,27,10)) AS no_rsa, 
                            substr(data,37,3) AS supplement_code,
                            1 as nombre
                        FROM w_out_porg
                        ) subview
                        JOIN temp.p_rsa ON subview.no_rsa = p_rsa.no_rsa
                    UNION
                    SELECT rss_id, supplement_code, nombre
                    FROM (
                        SELECT
                            base.cti_to_number(substr(data,27,10)) AS no_rsa, 
                            substr(data,37,3) AS supplement_code,
                            base.cti_to_number(substr(data,52,10)) as nombre
                        FROM w_out_pie
                        ) subview
                        JOIN temp.p_rsa ON subview.no_rsa = p_rsa.no_rsa
                    ) subview ON p_rss.oid = subview.rss_id 
                JOIN pmsi.t_prestations ON t_prestations.code = subview.supplement_code
                LEFT JOIN pmsi.t_prestation_tarif ON t_prestations.oid = t_prestation_tarif.prestation_id AND
                    p_rss.date_sortie BETWEEN t_prestation_tarif.date_debut AND t_prestation_tarif.date_fin AND 
                    t_prestation_tarif.type_ets = '2'   
                WHERE import_id = $import_id   "; 
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
    
    
    // IVG
    $sqlcmd = "INSERT INTO temp.p_rsf_detail(  
                finess, no_rss, nature, mt, dmt, date_debut, date_fin, nombre,   
                coefficient, prix_unitaire, base_remboursement, taux_remboursement,   
                sejour_facture, sejour_remboursable, compteur, ligne_t2a, pec_fj, pec_fj_id,   
                coefficient_mco, sejour_remboursable_2, ghs_id, sejour_rembourse_noemie,   
                nature_noemie, prestation_id, rss_id, type, coefficient_geo, est_ligne_rss, est_ligne_rum, no_rum, unite_medicale_id, base_remboursement_rum)   
            SELECT subview.finess, subview.no_rss, '', '', '', subview.date_entree, subview.date_sortie,   
                1 AS nombre,  
                1,   
                t_prestation_tarif.tarif AS prix_unitaire,  
                0, 100, 0, 0, '', '', '', 0, 1, 0, 0, 0, '', t_prestations.oid, subview.oid, 'B', 
                1,  '1', '0', 0, 0, 0  
            FROM
            (
                SELECT p_rss.oid, p_rss.no_rss, date_entree, date_sortie, p_rss.finess,
                    CASE  
                        WHEN MAX(case when t_actes_c.code LIKE 'JNJP%' then '1' else '0' end) = '1' THEN 'AMF'
                        WHEN MAX(case when activite_ccam = '4' then '1' else '0' end) = '1' AND MAX(duree_sejour) = 0 THEN 'AMD'
                        WHEN MAX(case when activite_ccam = '4' then '1' else '0' end) = '1' AND MAX(duree_sejour) IN (1,2) THEN 'APD'
                        WHEN MAX(duree_sejour) IN (1,2) THEN 'IPD'
                        ELSE 'IMD' END AS prestation_code
                FROM temp.p_rss
                JOIN pmsi.t_ghm ON t_ghm.oid = p_rss.ghm_id
                LEFT JOIN temp.p_rss_actes ON p_rss_actes.rss_id = p_rss.oid 
                LEFT JOIN pmsi.t_actes_c ON acte_id = t_actes_c.oid
                WHERE t_ghm.code = '14Z08Z' AND import_id = $import_id 
                GROUP BY 1,2,3,4,5
            ) subview
            JOIN pmsi.t_prestations ON prestation_code = t_prestations.code
            JOIN pmsi.t_prestation_tarif ON prestation_id = t_prestations.oid AND t_prestation_tarif.type_ets = '2'
            WHERE date_sortie BETWEEN t_prestation_tarif.date_debut AND t_prestation_tarif.date_fin "; 
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
    
    // Suppléments de transport d'après Fishsup
    logInfoMsg("Suppléments transport");
    
    // TDE sur mode de sortie = 7
    $nb_tde = 0;
    $nb_tse = 0;
    $nb_ms7 = 0;
    $tx_remb_tde = 100;
    
    // Nombre de TDE et TSE à ventiler
    $sqlcmd = "
        SELECT
            t_prestations.code,
            nb_sejours
        FROM
            temp.p_fichsup_transports
            JOIN pmsi.t_prestations ON t_prestations.oid = p_fichsup_transports.prestation_id
        WHERE 1=1
            AND import_id = $import_id
            AND t_prestations.code IN ('TDE', 'TSE')
        ORDER BY t_prestations.code";
    $result = $iCTI_connexion->query($sqlcmd);;
    while ($row = pg_fetch_row($result)) {
        if ($row[0] == 'TDE') {
            $nb_tde = $row[1] + 0;
        }
        else {
            $nb_tse = $row[1] + 0;
        }
    }
    
    // Nombre de séjours hospitalisés avec mode de sortie 7 Transfert définitif
    $sqlcmd = "
        SELECT count(*) 
        FROM temp.p_rss 
        WHERE 1=1
            AND ghm_id > 0 
            AND mode_sortie = '7'
            AND import_id = $import_id";
    $result = $iCTI_connexion->query($sqlcmd);;
    while ($row = pg_fetch_row($result)) {
        if (intval($row[0]) > 0) {
            $nb_ms7 = $row[0] + 0;
        }
    }
    
    if ($nb_tde > 0) {
        
        // calcul du taux de remboursement moyen sur N-1 pour les TDE
        // https://www.atih.sante.fr/sites/default/files/public/content/3369/notice_technique_complementaire_recueil_transports_n_cim-mf-559-6-2018.pdf
        // (calcul empirique...)
        // D'après un sujet sur Agora (https://agora.atih.sante.fr/agora/ago_action_theme.do?action=voir_sujet&id_sujet=53460#171522), 
        // il se calcule avec deux décimales sur les RSA valorisés, hors séances
        $annee_precedente = $annee_fin - 1;
        $sqlcmd = "
            SELECT
                round(avg(p_rsf_total.taux_remboursement), 2) as tx_remboursement
            FROM
                pmsi.p_rsf_total
                JOIN pmsi.p_rss on p_rss.oid = p_rsf_total.rss_id
                JOIN pmsi.t_ghm_c ON t_ghm_c.oid = p_rss.ghm_id
            WHERE 1=1
                AND p_rss.mois_sortie between " . $annee_precedente . "01 AND " . $annee_precedente . "12
                AND t_ghm_c.cmd_code != '28'
                AND traitement_epmsi = '30'
                AND en_cours = '0'
                AND p_rss.ghm_id > 0
                ";
        $result = $iCTI_connexion->query($sqlcmd);;
        while ($row = pg_fetch_row($result)) {
            if (intval($row[0]) > 0) {
                $tx_remb_tde = $row[0] + 0;
            }
        }
        
        $sqlcmd = "
            INSERT INTO temp.p_rsf_detail
                (rss_id, no_rss, date_debut, date_fin, prix_unitaire, taux_remboursement, prestation_id)
            SELECT
                  p_rss.oid
                , p_rss.no_rss
                , p_rss.date_entree
                , p_rss.date_sortie
                , t_prestation_tarif.tarif as prix_unitaire
                , $tx_remb_tde as taux_remboursement
                , t_prestations.oid as prestation_id
            FROM
                temp.p_rss
                JOIN pmsi.t_prestations ON t_prestations.code = 'TDE'
                JOIN pmsi.t_prestation_tarif
                    ON  t_prestations.oid = t_prestation_tarif.prestation_id
                    AND p_rss.date_sortie BETWEEN t_prestation_tarif.date_debut AND t_prestation_tarif.date_fin
                    AND t_prestation_tarif.type_ets = '2'
            WHERE 1=1
                AND import_id = $import_id
                AND p_rss.mode_sortie = '7'
                AND ghm_id > 0
            ORDER BY p_rss.date_sortie
            LIMIT $nb_tde";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
        
        // S'il y a plus de TDE que de séjours en MS7, on met au hasard les TDE supplémentaires sur les séjours avec sortie domicile
        if ($nb_tde > $nb_ms7) {
            $sqlcmd = "
                INSERT INTO temp.p_rsf_detail
                    (rss_id, no_rss, date_debut, date_fin, prix_unitaire, taux_remboursement, prestation_id)
                SELECT
                      p_rss.oid
                    , p_rss.no_rss
                    , p_rss.date_entree
                    , p_rss.date_sortie
                    , t_prestation_tarif.tarif as prix_unitaire
                    , 100 as taux_remboursement
                    , t_prestations.oid as prestation_id
                FROM
                    temp.p_rss
                    JOIN pmsi.t_prestations ON t_prestations.code = 'TDE'
                    JOIN pmsi.t_prestation_tarif
                        ON  t_prestations.oid = t_prestation_tarif.prestation_id
                        AND p_rss.date_sortie BETWEEN t_prestation_tarif.date_debut AND t_prestation_tarif.date_fin
                        AND t_prestation_tarif.type_ets = '2'
                WHERE 1=1
                    AND import_id = $import_id
                    AND p_rss.mode_sortie = '8'
                    AND ghm_id > 0
                ORDER BY p_rss.date_sortie
                LIMIT " . $nb_tde - $nb_ms7;
            $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
        }
    }
    
    // On ventile au hasard les TSE sur les séjours avec retour à domicile qui n'ont pas déjà de TDE
    if ($nb_tse > 0) {
        $sqlcmd = "
            INSERT INTO temp.p_rsf_detail
                (rss_id, no_rss, date_debut, date_fin, prix_unitaire, taux_remboursement, prestation_id)
            SELECT
                  p_rss.oid
                , p_rss.no_rss
                , p_rss.date_entree
                , p_rss.date_sortie
                , t_prestation_tarif.tarif as prix_unitaire
                , 100 as taux_remboursement
                , t_prestations.oid as prestation_id
            FROM
                temp.p_rss
                JOIN pmsi.t_prestations ON t_prestations.code = 'TSE'
                JOIN pmsi.t_prestation_tarif
                    ON  t_prestations.oid = t_prestation_tarif.prestation_id
                    AND p_rss.date_sortie BETWEEN t_prestation_tarif.date_debut AND t_prestation_tarif.date_fin
                    AND t_prestation_tarif.type_ets = '2'
            WHERE 1=1
                AND import_id = $import_id
                AND p_rss.mode_sortie = '8'
                AND ghm_id > 0
                AND p_rss.oid != ALL (ARRAY(SELECT 
                                                rss_id 
                                            FROM 
                                                temp.p_rsf_detail 
                                                JOIN temp.p_rss ON p_rss.oid = p_rsf_detail.rss_id
                                                JOIN pmsi.t_prestations ON t_prestations.oid = p_rsf_detail.prestation_id
                                            WHERE 1=1
                                                AND p_rss.import_id = $import_id
                                                AND t_prestations.code = 'TDE'
                                            )::bigint[])
            ORDER BY p_rss.date_sortie
            LIMIT $nb_tse";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    }
    
    
    // Totaux Facture
    logInfoMsg("Valorisation Facture");
    
    // Coefficient mco
    $sqlcmd = "UPDATE temp.p_rsf_detail SET 
                    coefficient_mco = v_coefficient_mco.coefficient_mco_calcul,
                    coefficient_geo = v_coefficient_mco.coef_geo,
                    coefficient_pacte_resp = v_coefficient_mco.coef_cice,
                    update_rules = array_append(update_rules, 30)
        FROM 
            pmsi.t_prestations, base.v_coefficient_mco, temp.p_rss 
        WHERE  p_rsf_detail.prestation_id = t_prestations.oid
            AND p_rsf_detail.rss_id = p_rss.oid
            AND p_rss.finess = v_coefficient_mco.finess
            AND p_rss.import_id = $import_id
            AND p_rsf_detail.est_ligne_rss = '1'
            AND p_rss.date_sortie BETWEEN base.v_coefficient_mco.date_debut AND base.v_coefficient_mco.date_fin
            AND  p_rsf_detail.type = 'B'  
            AND t_prestations.code IN (
                'GHS', 'EXH', 'REA', 'REP', 'RAP', 'SRC', 'STF', 'NN1', 'NN2', 'NN3', 'DIP', 'D09', 'D17', 'D18', 'D19', 'OHB', 'IRRE0', 
                'IRRE1', 'IRRE2', 'IRRE3', 'IRRE4', 'IRRE5', 'IRRE6', 'IRRE7', 'IRRE8', 'IRRE9', 'IRRE10',
                'IRRE11', 'IRRE12', 'APHE', 'ANT', 'PO1', 'PO2', 'PO3', 'PO4', 'PO5', 'PO6', 'PO7', 'PO8', 'PO9', 'POA', 'SDC',
                'TDE', 'TDE1', 'TDE2', 'TDE3', 'TDE4', 'TDE5', 'TSE', 'TSE6', 'TSE7', 'TSE8', 'TSE9' 
            )
    ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();

    
    // Valorisation GHS
    $sqlcmd = "UPDATE temp.p_rsf_detail 
        SET coefficient = CASE WHEN t_prestations.code = 'GHS' AND sejour_rembourse_noemie <> 0 THEN sejour_rembourse_noemie / prix_unitaire / nombre ELSE 1 END, 
        base_remboursement = round(sejour_rembourse_noemie * coefficient_mco,2), 
        base_remboursement_sauf_transition = round(sejour_rembourse_noemie * coefficient_geo * coefficient_pacte_resp,2), 
        sejour_rembourse_noemie = 0 ,
        update_rules = array_append(update_rules, 32)
        FROM 
        temp.p_rss, pmsi.t_prestations 
        WHERE import_id = $import_id 
        AND p_rsf_detail.rss_id = p_rss.oid AND  p_rsf_detail.type = 'B'  AND p_rsf_detail.est_ligne_rss = '1'
        AND p_rsf_detail.prestation_id = t_prestations.oid 
        AND t_prestations.code IN ('GHS', 'EXH') ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
    
    // Valorisation suppléments
    $sqlcmd = "
        UPDATE temp.p_rsf_detail
        SET 
            base_remboursement = round(nombre * prix_unitaire * coefficient_mco,2),
            base_remboursement_sauf_transition = round(nombre * prix_unitaire * coefficient_geo * coefficient_pacte_resp,2),
            sejour_rembourse_noemie = 0,
            update_rules = array_append(update_rules, 35)
        FROM temp.p_rss, pmsi.t_prestations
        WHERE 1=1
            AND import_id = $import_id
            AND p_rsf_detail.rss_id = p_rss.oid AND  p_rsf_detail.type = 'B' AND p_rsf_detail.est_ligne_rss = '1'
            AND p_rsf_detail.prestation_id = t_prestations.oid
            AND t_prestations.code IN 
                (
                'REA', 'REP', 'RAP', 'SRC', 'STF', 'NN1', 'NN2', 'NN3', 'DIP', 'D09', 'D17', 'D18', 'D19', 'OHB', 'IRRE0', 'IRRE1', 'IRRE2', 
                'IRRE3', 'IRRE4', 'IRRE5', 'IRRE6', 'IRRE7', 'IRRE8', 'IRRE9', 'IRRE10', 'IRRE11', 'IRRE12', 'APHE',
                'ANT', 'AMD', 'AMF', 'APD', 'IMD', 'IPD', 'FJS', 'PO1', 'PO2', 'PO3', 'PO4', 'PO5', 'PO6', 'PO7', 'PO8', 'PO9', 'POA', 'SDC',
                'TDE', 'TDE1', 'TDE2', 'TDE3', 'TDE4', 'TDE5', 'TSE', 'TSE6', 'TSE7', 'TSE8', 'TSE9'
                ) 
    ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    
    
    // Prestations lpp
    
    $sqlcmd = "INSERT INTO temp.p_rsf_detail( 
            finess, no_rss, nature, mt, dmt, date_debut, date_fin, nombre,  
            coefficient, prix_unitaire, base_remboursement, base_remboursement_sauf_transition, taux_remboursement,  
            sejour_facture, sejour_remboursable, compteur, ligne_t2a, pec_fj, pec_fj_id,  
            coefficient_mco, sejour_remboursable_2, ghs_id, sejour_rembourse_noemie,  
            nature_noemie, prestation_id, rss_id, type, coefficient_geo, est_ligne_rss, est_ligne_rum, no_rum, unite_medicale_id, base_remboursement_rum)  
            SELECT p_rss.finess, p_rss.no_rss, '', '', '', date_lpp, date_lpp, nombre, 
                1, p_rss_lpp.prix_unitaire, montant_facture, montant_facture, 100, montant_facture, montant_facture, '', '', '', 0, 
                1, 0, 0, montant_facture, '', t_lpp.prestation_defaut_id, rss_id, 'B', 1, '1', '0', 0, 0, 0 
            FROM temp.p_rss_lpp
                JOIN temp.p_rss ON p_rss_lpp.rss_id = p_rss.oid
                JOIN pmsi.t_lpp ON p_rss_lpp.lpp_id = t_lpp.oid 
            WHERE p_rss.ghm_id > 0 
                AND (p_rss.mode_entree <> '0' AND p_rss.mode_sortie <> '0')
                AND montant_facture <> 0 AND non_pris_en_compte <> '1'; ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    // Ecarts LPP
    
    $sqlcmd = "INSERT INTO temp.p_rsf_detail( 
            finess, no_rss, nature, mt, dmt, date_debut, date_fin, nombre,  
            coefficient, prix_unitaire, base_remboursement, base_remboursement_sauf_transition, taux_remboursement,  
            sejour_facture, sejour_remboursable, compteur, ligne_t2a, pec_fj, pec_fj_id,  
            coefficient_mco, sejour_remboursable_2, ghs_id, sejour_rembourse_noemie,  
            nature_noemie, prestation_id, rss_id, type, coefficient_geo, est_ligne_rss, est_ligne_rum, no_rum, unite_medicale_id, base_remboursement_rum)  
            SELECT p_rss.finess, p_rss.no_rss, '', '', '', date_lpp, date_lpp, nombre, 
                1, p_rss_lpp.montant_ecart_indemnisable / nombre, montant_ecart_indemnisable, montant_ecart_indemnisable, 100, montant_ecart_indemnisable, montant_ecart_indemnisable, '', '', '', 0, 
                1, 0, 0, montant_ecart_indemnisable, '', t_prestations.oid, rss_id, 'B', 1, '1', '0', 0, 0, 0 
            FROM temp.p_rss_lpp
                JOIN temp.p_rss ON p_rss_lpp.rss_id = p_rss.oid
                JOIN pmsi.t_lpp ON p_rss_lpp.lpp_id = t_lpp.oid 
                JOIN pmsi.t_prestations ON t_prestations.code = 'ETI'
            WHERE p_rss.ghm_id > 0 
                AND (p_rss.mode_entree <> '0' AND p_rss.mode_sortie <> '0') 
                AND montant_ecart_indemnisable <> 0 AND non_pris_en_compte <> '1'; ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    
    // Prestation pharmacie
    $sqlcmd = "INSERT INTO temp.p_rsf_detail( 
                finess, no_rss, nature, mt, dmt, date_debut, date_fin, nombre,  
                coefficient, prix_unitaire, base_remboursement, base_remboursement_sauf_transition, taux_remboursement,  
                sejour_facture, sejour_remboursable, compteur, ligne_t2a, pec_fj, pec_fj_id,  
                coefficient_mco, sejour_remboursable_2, ghs_id, sejour_rembourse_noemie,  
                nature_noemie, prestation_id, rss_id, type, coefficient_geo, est_ligne_rss, est_ligne_rum, no_rum, unite_medicale_id, base_remboursement_rum)  
            SELECT p_rss.finess, p_rss.no_rss, '', '', '', date_ucd, date_ucd, nombre, 
                1, p_rss_ucd.montant_facture / p_rss_ucd.nombre, montant_facture, montant_facture, 100, montant_facture, montant_facture, '', '', '', 0, 
                1, 0, 0, montant_facture, '', CASE WHEN t_ucd.prestation_defaut_id > 0 THEN t_ucd.prestation_defaut_id ELSE COALESCE(t_prestations.oid,0) END, rss_id, 'B', 1, '1', '0', 0, 0, 0
            FROM temp.p_rss_ucd
                JOIN temp.p_rss ON p_rss_ucd.rss_id = p_rss.oid 
                JOIN pmsi.t_ucd ON p_rss_ucd.ucd_id = t_ucd.oid 
                JOIN pmsi.t_type_ucd ON t_type_ucd.oid = p_rss_ucd.type_ucd_id
				LEFT JOIN pmsi.t_prestations ON t_prestations.code = 'PHH'
            WHERE (p_rss.mode_entree <> '0' AND p_rss.mode_sortie <> '0') AND
                montant_facture <> 0 AND non_pris_en_compte <> '1'
                AND (t_type_ucd.code = 'SUS' OR t_type_ucd.code = 'ATU'); ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    // Ecart pharmacie
    $sqlcmd = "INSERT INTO temp.p_rsf_detail( 
            finess, no_rss, nature, mt, dmt, date_debut, date_fin, nombre,  
            coefficient, prix_unitaire, base_remboursement, base_remboursement_sauf_transition, taux_remboursement,  
            sejour_facture, sejour_remboursable, compteur, ligne_t2a, pec_fj, pec_fj_id,  
            coefficient_mco, sejour_remboursable_2, ghs_id, sejour_rembourse_noemie,  
            nature_noemie, prestation_id, rss_id, type, coefficient_geo, est_ligne_rss, est_ligne_rum, no_rum, unite_medicale_id, base_remboursement_rum)  
            SELECT p_rss.finess, p_rss.no_rss, '', '', '', date_ucd, date_ucd, nombre, 
                1, p_rss_ucd.montant_ecart_indemnisable / p_rss_ucd.nombre, montant_ecart_indemnisable, montant_ecart_indemnisable, 100, montant_ecart_indemnisable, montant_ecart_indemnisable, '', '', '', 0, 
                1, 0, 0, montant_ecart_indemnisable, '', t_prestations.oid, rss_id, 'B', 1, '1', '0', 0, 0, 0
            FROM temp.p_rss_ucd
                JOIN temp.p_rss ON p_rss_ucd.rss_id = p_rss.oid 
                JOIN pmsi.t_ucd ON p_rss_ucd.ucd_id = t_ucd.oid 
                JOIN pmsi.t_type_ucd ON t_type_ucd.oid = p_rss_ucd.type_ucd_id
                JOIN pmsi.t_prestations ON t_prestations.code = 'EMI'
            WHERE (p_rss.mode_entree <> '0' AND p_rss.mode_sortie <> '0') AND
                montant_ecart_indemnisable <> 0 AND non_pris_en_compte <> '1'
                AND t_type_ucd.code = 'SUS';";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();

    // Ajustement p_vidhosp
    
    // Prise en charge forfait journalier
    $sqlcmd = "UPDATE temp.p_vidhosp
                SET code_pec_fj = 'X',
                    code_pec_fj_id = t_pec_fj.oid
                FROM temp.p_rss 
                JOIN pmsi.t_ghm ON ghm_id = t_ghm.oid
                JOIN base.t_pec_fj ON t_pec_fj.code = 'X'
                WHERE p_vidhosp.rss_id = p_rss.oid AND
                    code_pec_fj <> 'X' AND
                    (code_pec = '1' AND duree_sejour = 0 OR
                    code_pec = '1' AND t_ghm.code LIKE '15%' OR
                    code_pec = '1' AND t_ghm.code LIKE '28%' OR
                    code_pec = '1' AND t_ghm.code in ('23K02Z' , '14Z08Z')
                    )";
    //$toResult = execute_sql($sqlcmd, $nbE, $nbW );
    //commit_trans();
    
    
    
    // taux remboursement calcule vidhosp
        $sqlcmd = "DROP TABLE IF EXISTS w_rsf_detail_po;
                    CREATE TEMP TABLE w_rsf_detail_po AS
                    SELECT rss_id AS rss_id_po 
                        FROM temp.p_rsf_detail
                        JOIN pmsi.t_prestations ON prestation_id = t_prestations.oid
                        WHERE t_prestations.code IN ('PO1', 'PO2', 'PO3', 'PO4', 'PO5', 'PO6', 'PO7', 'PO8', 'PO9', 'POA')
                    GROUP BY 1";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );
        commit_trans();
    
        $sqlcmd = "UPDATE temp.p_vidhosp
                SET taux_remboursement_calcule =
                CASE 
                    WHEN p_rss.date_entree - p_rss.date_naissance <= 30 THEN 100
                    WHEN t_ghm.code IN ('28Z08Z', '28Z09Z', '28Z11Z', '28Z12Z', '28Z13Z', '28Z18Z', '28Z19Z', '28Z20Z', '28Z21Z', '28Z22Z', '28Z23Z', '28Z24Z', '28Z25Z') THEN 100
                    WHEN rss_id_po IS NOT NULL THEN 100
                    WHEN p_vidhosp.code_pec = '2' THEN 80
                    WHEN p_vidhosp.nature_pec IN ('30','41','90') THEN 100
                    WHEN p_vidhosp.justificatif_exo = '9' AND p_vidhosp.nature_pec = '10' THEN 90
                    WHEN p_vidhosp.justificatif_exo NOT IN ('0','2') THEN 100
                    ELSE 80 END
                FROM temp.p_rss
                JOIN pmsi.t_ghm ON ghm_id = t_ghm.oid
                LEFT JOIN w_rsf_detail_po ON p_rss.oid = w_rsf_detail_po.rss_id_po
                WHERE p_vidhosp.rss_id = p_rss.oid";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );
        commit_trans();
        
        // taux remboursement et forfait utilise vidhosp
        $sqlcmd = "UPDATE temp.p_vidhosp SET
                    taux_remboursement_utilise = 
                        CASE 
                            WHEN p_rss.date_entree - p_rss.date_naissance <= 30 THEN 100
                            WHEN t_ghm.code IN ('28Z08Z', '28Z09Z', '28Z11Z', '28Z12Z', '28Z13Z', '28Z18Z', '28Z19Z', '28Z20Z', '28Z21Z', '28Z22Z', '28Z23Z', '28Z24Z', '28Z25Z') THEN 100
                            WHEN rss_id_po IS NOT NULL THEN 100
                            WHEN p_vidhosp.code_pec IN ('2','3') AND p_vidhosp.taux_remboursement NOT IN (80,90) THEN 80
                            WHEN p_vidhosp.taux_remboursement IN (80,90,100) THEN p_vidhosp.taux_remboursement 
                            ELSE p_vidhosp.taux_remboursement_calcule 
                        END,
                    code_pec_fj_utilise = 
                        CASE 
                            WHEN p_rss.date_entree - p_rss.date_naissance <= 30 THEN 'E'
                            WHEN t_ghm.code IN ('28Z08Z', '28Z09Z', '28Z11Z', '28Z12Z', '28Z13Z', '28Z18Z', '28Z19Z', '28Z20Z', '28Z21Z', '28Z22Z', '28Z23Z', '28Z24Z', '28Z25Z') THEN 'X'
                            WHEN rss_id_po IS NOT NULL THEN 'X'
                            WHEN t_pec.code IN ('2') THEN 'A'
                            WHEN p_rss.duree_sejour = 0 THEN 'X'
                            WHEN p_rss.mois_sortie < 201501 AND t_ghm.code LIKE '15%' THEN 'X'
                            WHEN t_ghm.code LIKE '28%' THEN 'X'
                            WHEN t_ghm.code in ('23K02Z' , '14Z08Z') THEN 'X'
                            WHEN t_pec_fj.code = 'X' THEN 'X'
                            WHEN t_pec_fj.code = 'L' THEN 'E'
                            WHEN t_pec_fj.code = 'R' THEN 'E'
                            WHEN p_vidhosp.nature_pec IN ('13','41') THEN 'E' 
                            WHEN t_pec_fj.code = 'A' THEN 'A'
                            ELSE '' END
                    FROM temp.p_rss 
                        JOIN temp.p_vidhosp p_vidhosp2 ON p_rss.oid = p_vidhosp2.rss_id
                        JOIN base.t_pec ON p_vidhosp2.code_pec_id = t_pec.oid
                        JOIN base.t_pec_fj ON p_vidhosp2.code_pec_fj_id = t_pec_fj.oid
                        JOIN pmsi.t_ghm on ghm_id = t_ghm.oid
                        LEFT JOIN w_rsf_detail_po ON p_rss.oid = w_rsf_detail_po.rss_id_po
                    WHERE p_rss.oid = p_vidhosp.rss_id";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );
        commit_trans();
    
    // montant remboursable
    $sqlcmd = "UPDATE temp.p_rsf_detail 
                SET 
                    taux_remboursement = p_vidhosp.taux_remboursement_utilise,
                    sejour_remboursable = round(p_rsf_detail.base_remboursement * p_vidhosp.taux_remboursement_utilise / 100,2),
                    sejour_remboursable_2 = round(p_rsf_detail.base_remboursement * (100 - p_vidhosp.taux_remboursement_utilise) / 100,2),
                    update_rules = array_append(update_rules, 36)
                FROM pmsi.t_prestations, temp.p_rss, temp.p_vidhosp, base.t_pec
                WHERE p_rsf_detail.prestation_id = t_prestations.oid 
                    AND t_pec.oid = p_vidhosp.code_pec_id
                    AND p_rss.import_id = $import_id
                    AND p_rsf_detail.rss_id = p_rss.oid AND p_vidhosp.rss_id = p_rss.oid AND p_rsf_detail.type = 'B' AND p_rsf_detail.est_ligne_rss = '1' 
                    AND ghm_id > 0
                    AND t_prestations.code NOT IN ('GHS','EMI','ETI','TDE','TSE')
                    AND p_rsf_detail.prestation_id != ALL (ARRAY(SELECT prestation_defaut_id FROM pmsi.t_lpp WHERE prestation_defaut_id <> 0 GROUP BY 1)::bigint[])
                    AND p_rsf_detail.prestation_id != ALL (ARRAY(SELECT prestation_defaut_id FROM pmsi.t_ucd WHERE prestation_defaut_id <> 0 GROUP BY 1)::bigint[])
                    AND (
                        p_rsf_detail.taux_remboursement <> p_vidhosp.taux_remboursement_utilise OR
                        p_rsf_detail.sejour_remboursable <> round(p_rsf_detail.base_remboursement * p_vidhosp.taux_remboursement_utilise / 100,2) OR
                        sejour_remboursable_2 <> round(p_rsf_detail.base_remboursement * (100 - p_vidhosp.taux_remboursement_utilise) / 100,2)
                        );";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();


    // CLA 2019-03-06 : Passage de la participation forfaitaire de 18 à 24 euros au 01/01/2019
    $sqlcmd = "UPDATE temp.p_rsf_detail 
                SET 
                    taux_remboursement = p_vidhosp.taux_remboursement_utilise,
                    sejour_remboursable = 
                        p_rsf_detail.base_remboursement
                        -   (CASE 
                            WHEN 
                                p_rsf_detail.base_remboursement > 0 AND 
                                t_exoneration_tm.code NOT IN ('X') AND 
                                p_vidhosp.taux_remboursement_utilise = 100 AND 
                                t_ghm.code NOT LIKE '28%' AND
                                p_vidhosp.nature_pec NOT IN ('13') AND
                                t_facturation_18euros.code = '1' 
                                THEN 24 
                            ELSE 0 
                            END)
                        -   (CASE 
                            WHEN p_rsf_detail.base_remboursement > 0 AND 
                                p_vidhosp.taux_remboursement_utilise = 100 AND 
                                code_pec_fj_utilise = 'A' AND
                                mode_sortie NOT IN ('7','9') THEN (p_rss.date_sortie - p_rss.date_entree + 1) * 20
                            WHEN p_rsf_detail.base_remboursement > 0 AND 
                                p_vidhosp.taux_remboursement_utilise = 100 AND 
                                code_pec_fj_utilise = 'A' AND
                                mode_sortie IN ('9') THEN (p_rss.date_sortie - p_rss.date_entree) *  20
                            WHEN p_rsf_detail.base_remboursement > 0 AND 
                                p_vidhosp.taux_remboursement_utilise = 100 AND 
                                code_pec_fj_utilise = 'A' AND
                                mode_sortie IN ('7') THEN (p_rss.date_sortie - p_rss.date_entree) *  20
                            ELSE 
                            0
                            END)
                        -   round((p_rsf_detail.base_remboursement * (100 - p_vidhosp.taux_remboursement_utilise) / 100),2) ,
                    update_rules = array_append(update_rules, 37)
                FROM pmsi.t_prestations, 
                    temp.p_rss
                    JOIN temp.p_vidhosp ON p_vidhosp.rss_id = p_rss.oid
                    JOIN base.t_exoneration_tm ON p_vidhosp.exoneration_tm_id = t_exoneration_tm.oid
                    JOIN base.t_facturation_18euros ON p_vidhosp.facturation_18euros_id = t_facturation_18euros.oid
                    JOIN base.t_pec_fj ON p_vidhosp.code_pec_fj_id = t_pec_fj.oid
                    JOIN pmsi.t_ghm ON p_rss.ghm_id = t_ghm.oid
                WHERE p_rsf_detail.prestation_id = t_prestations.oid AND
                    p_rss.import_id = $import_id AND
                    p_rsf_detail.rss_id = p_rss.oid AND
                    p_rsf_detail.type = 'B' AND 
                    p_rsf_detail.est_ligne_rss = '1' AND
                    ghm_id > 0 AND
                    t_prestations.code = 'GHS' AND
                    (
                        p_rsf_detail.taux_remboursement <> p_vidhosp.taux_remboursement_utilise OR
                    
                        sejour_remboursable <> 
                            (p_rsf_detail.base_remboursement
                        -   (CASE 
                            WHEN 
                                p_rsf_detail.base_remboursement > 0 AND 
                                t_exoneration_tm.code NOT IN ('X') AND 
                                p_vidhosp.taux_remboursement_utilise = 100 AND 
                                t_ghm.code NOT LIKE '28%' AND
                                p_vidhosp.nature_pec NOT IN ('13') AND
                                t_facturation_18euros.code = '1' 
                                THEN 24 
                            ELSE 0 
                            END)
                        -   (CASE 
                            WHEN p_rsf_detail.base_remboursement > 0 AND 
                                p_vidhosp.taux_remboursement_utilise = 100 AND 
                                p_vidhosp.code_pec_fj_utilise = 'A' AND
                                mode_sortie NOT IN ('7','9') THEN (p_rss.date_sortie - p_rss.date_entree + 1) * 20 
                            WHEN p_rsf_detail.base_remboursement > 0 AND 
                                p_vidhosp.taux_remboursement_utilise = 100 AND 
                                p_vidhosp.code_pec_fj_utilise = 'A' AND
                                mode_sortie IN ('9') THEN (p_rss.date_sortie - p_rss.date_entree) * 20 
                            WHEN p_rsf_detail.base_remboursement > 0 AND 
                                p_vidhosp.taux_remboursement_utilise = 100 AND 
                                p_vidhosp.code_pec_fj_utilise = 'A' AND
                                mode_sortie IN ('7') THEN (p_rss.date_sortie - p_rss.date_entree) * 20 
                            ELSE 
                            0
                            END)
                        -   round((p_rsf_detail.base_remboursement * (100 - p_vidhosp.taux_remboursement_utilise) / 100),2) )

                        );
    ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();


    logInfoMsg("EXH a 100% sur dossier a 80% si duree > 30j");
    // Sur EXH, Attention, après 30jours, facturation à 100%
    
    // Identification des EXH à 80% pour une durée de séjour > 30j
    $sqlcmd = "DROP TABLE IF EXISTS w_exh_30;
            CREATE TEMP TABLE w_exh_30 AS
            SELECT p_rsf_detail.CTID AS from_CTID,
                p_rsf_detail.base_remboursement / p_rsf_detail.nombre AS prix_unitaire_reel,
                p_rsf_detail.base_remboursement_sauf_transition / p_rsf_detail.nombre AS prix_unitaire_reel_sauf_transition,
                CASE WHEN mode_sortie = '9' THEN date_sortie - date_entree + 1 ELSE date_sortie - date_entree END AS duree_sejour_facturee,
                0::numeric AS nombre_100,
                0::numeric AS base_remboursement_100,
                0::numeric AS base_remboursement_sauf_transition_100,
                0::numeric AS sejour_remboursable_100,
                0::numeric AS nombre_80,
                0::numeric AS sejour_remboursable_80,
                0::numeric AS base_remboursement_80,
                0::numeric AS base_remboursement_sauf_transition_80,
                p_rsf_detail.*
            FROM temp.p_rsf_detail
            JOIN pmsi.t_prestations on t_prestations.oid = prestation_id AND t_prestations.code = 'EXH'
            JOIN temp.p_rss on p_rsf_detail.rss_id = p_rss.oid
            WHERE p_rsf_detail.taux_remboursement <> 100 AND est_ligne_rss = '1' AND 
                p_rss.duree_sejour > 30;";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();

    // Calcul nouveaux remboursement (80% <= 30j et 100% > 30j)
    $sqlcmd = "UPDATE w_exh_30 SET
                nombre_100 = duree_sejour_facturee - 30,
                nombre_80 = nombre - (duree_sejour_facturee - 30);
            UPDATE w_exh_30 SET
                nombre_100 = nombre_100 + nombre_80,
                nombre_80 = 0
            WHERE nombre_80 < 0;
            UPDATE w_exh_30 SET
                base_remboursement_100 = round(nombre_100 * prix_unitaire_reel,2),
                base_remboursement_sauf_transition_100 = round(nombre_100 * prix_unitaire_reel_sauf_transition,2),
                sejour_remboursable_100 = round(nombre_100 * prix_unitaire_reel,2),
                sejour_remboursable_80 = round(nombre_80 * prix_unitaire_reel * 80 / 100,2),
                base_remboursement_80 = base_remboursement - round(nombre_100 * prix_unitaire_reel,2),
                base_remboursement_sauf_transition_80 = base_remboursement_sauf_transition - round(nombre_100 * prix_unitaire_reel_sauf_transition,2);";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();

    // Mise à jour lignes existantes : 80%
    $sqlcmd = "UPDATE temp.p_rsf_detail SET
                nombre = nombre_80,
                base_remboursement = base_remboursement_80,
                base_remboursement_sauf_transition = base_remboursement_sauf_transition_80,
                sejour_remboursable = sejour_remboursable_80,
                update_rules = array_append(p_rsf_detail.update_rules, 39)
            FROM w_exh_30
            WHERE p_rsf_detail.CTID = from_CTID;";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();

    // Suppression ligne à 80 si borne haute > 30
    $sqlcmd = "DELETE FROM temp.p_rsf_detail
            USING w_exh_30 
            WHERE w_exh_30.rss_id = p_rsf_detail.rss_id AND
                w_exh_30.prestation_id = p_rsf_detail.prestation_id AND
                p_rsf_detail.nombre = 0 AND
                p_rsf_detail.taux_remboursement <> 100";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();

    // Ajout lignes à 100%
    $sqlcmd = "INSERT INTO temp.p_rsf_detail(
                finess, no_rss, nature, mt, dmt, date_debut, date_fin, nombre, 
                coefficient, prix_unitaire, base_remboursement, taux_remboursement, 
                sejour_facture, sejour_remboursable, compteur, ligne_t2a, pec_fj, 
                coefficient_mco, sejour_remboursable_2, ghs_id, sejour_rembourse_noemie, 
                nature_noemie, prestation_id, rss_id, type, coefficient_geo, 
                est_ligne_rss, est_ligne_rum, no_rum, unite_medicale_id, base_remboursement_rum, 
                montant_supplement_nf, sejour_remboursable_rum, pec_fj_id, base_remboursement_sauf_transition, 
                base_remboursement_rum_sauf_transition)
            SELECT 
                finess, no_rss, nature, mt, dmt, date_debut, date_fin, nombre_100 AS nombre, 
                coefficient, prix_unitaire, base_remboursement_100 AS base_remboursement, 100 AS taux_remboursement, 
                sejour_facture, sejour_remboursable_100 AS sejour_remboursable, compteur, ligne_t2a, pec_fj, 
                coefficient_mco, sejour_remboursable_2, ghs_id, sejour_rembourse_noemie, 
                nature_noemie, prestation_id, rss_id, type, coefficient_geo, 
                est_ligne_rss, est_ligne_rum, no_rum, unite_medicale_id, base_remboursement_rum, 
                montant_supplement_nf, sejour_remboursable_rum, pec_fj_id, base_remboursement_sauf_transition_100 AS base_remboursement_sauf_transition, 
                base_remboursement_rum_sauf_transition
            FROM w_exh_30;";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
	
	if ($file_exists_FCP) {
		logInfoMsg("Fichcomp transport");
		$sqlcmd = "
			DROP TABLE IF EXISTS w_in_transp;
			CREATE TEMP TABLE w_in_transp (data text, 
				no_sejour text, 
				prestation_date date, 
				prestation_code text, 
				prestation_id bigint,
				rss_id bigint,
				coefficient_mco numeric,
				taux_remboursement numeric,
				prix_unitaire numeric
			);

			COPY w_in_transp(data) FROM '$file_FCP' WITH DELIMITER AS E'\01'
			;
			
			DELETE FROM w_in_transp
			WHERE substr(data,10,2) <> '15'
			;

			UPDATE w_in_transp SET
				no_sejour = trim(substr(data,12,20)),
				prestation_date = base.cti_to_date(trim(substr(data,41,8))),
				prestation_code = trim(substr(data,49,3)) || base.cti_to_number(trim(substr(data,52,2)))
			;

			UPDATE w_in_transp
			SET rss_id = p_rss.oid
			FROM temp.p_rss
			WHERE no_sejour_administratif = no_sejour AND
				prestation_date BETWEEN date_entree AND date_sortie
			;
			
			UPDATE w_in_transp
			SET rss_id = p_rss.oid
			FROM temp.p_rss
			WHERE w_in_transp.rss_id IS NULL AND
				substr(no_sejour_administratif,2) = no_sejour AND
				no_sejour_administratif BETWEEN 'A' AND 'Z99999' AND
				prestation_date BETWEEN date_entree AND date_sortie
			;

			UPDATE w_in_transp SET 
				coefficient_mco = p_rsf_detail.coefficient_mco,
				taux_remboursement = p_rsf_detail.taux_remboursement
			FROM temp.p_rsf_detail
			JOIN pmsi.t_prestations ON prestation_id = t_prestations.oid
			WHERE w_in_transp.rss_id = p_rsf_detail.rss_id AND
				t_prestations.code = 'GHS'
			;

			UPDATE w_in_transp SET
				prestation_id = t_prestations.oid,
				prix_unitaire = t_prestation_tarif.tarif
			FROM pmsi.t_prestations
			JOIN pmsi.t_prestation_tarif ON t_prestation_tarif.prestation_id = t_prestations.oid
			WHERE prestation_code = t_prestations.code AND
				prestation_date BETWEEN t_prestation_tarif.date_debut AND t_prestation_tarif.date_fin AND
				t_prestation_tarif.type_ets = '2'
			;

			UPDATE w_in_transp SET
				prestation_id = t_prestations.oid,
				prix_unitaire = t_prestation_tarif.tarif
			FROM pmsi.t_prestations
			JOIN pmsi.t_prestation_tarif ON t_prestation_tarif.prestation_id = t_prestations.oid
			WHERE w_in_transp.prestation_id IS NULL AND 
				substr(prestation_code,1,3) = t_prestations.code AND
				prestation_date BETWEEN t_prestation_tarif.date_debut AND t_prestation_tarif.date_fin AND
				t_prestation_tarif.type_ets = '2'
			;



			INSERT INTO temp.p_rsf_detail(  
				finess, 
				no_rss, 
				nature, 
				mt, 
				dmt, 
				date_debut, 
				date_fin, 
				nombre,   
				coefficient, 
				prix_unitaire, 
				base_remboursement, 
				taux_remboursement,   
				sejour_facture, 
				sejour_remboursable, 
				compteur, 
				ligne_t2a, 
				pec_fj, 
				pec_fj_id,   
				coefficient_mco, 
				sejour_remboursable_2, 
				ghs_id, 
				sejour_rembourse_noemie,   
				nature_noemie, 
				prestation_id, 
				rss_id, 
				type, 
				coefficient_geo, 
				est_ligne_rss, 
				est_ligne_rum, 
				no_rum, 
				unite_medicale_id, 
				base_remboursement_rum)   
			SELECT p_rss.finess, 
				p_rss.no_rss, 
				'' AS nature, 
				'' AS mt, 
				'' AS dmt, 
				prestation_date AS date_debut, 
				prestation_date AS date_fin,   
				1 AS nombre,  
				1 AS coefficient,   
				w_in_transp.prix_unitaire, 
				round(w_in_transp.prix_unitaire * w_in_transp.coefficient_mco,2) AS base_remboursement,
				w_in_transp.taux_remboursement, 
				round(w_in_transp.prix_unitaire * w_in_transp.coefficient_mco,2) AS sejour_facture, 
				round(w_in_transp.prix_unitaire * w_in_transp.coefficient_mco * taux_remboursement / 100,2) AS sejour_remboursable, 
				'' AS compteur, 
				'' AS ligne_t2a, 
				'' AS pec_fj, 
				0 AS pec_fj_id, 
				w_in_transp.coefficient_mco, 
				0 AS sejour_remboursable_2, 
				0 AS ghs_id, 
				0 AS sejour_rembourse_noemie, 
				'' AS nature_noemie, 
				w_in_transp.prestation_id, 
				w_in_transp.rss_id, 
				'B' AS type, 
				1 AS coefficient_geo, 
				'1' AS est_ligne_rss, 
				'0' AS est_ligne_rum, 
				0 AS no_rum, 
				0 AS unite_medicale_id, 
				0 AS base_remboursement_rum
			FROM w_in_transp
			JOIN temp.p_rss ON w_in_transp.rss_id = p_rss.oid"
			;
			
		$toResult = execute_sql($sqlcmd, $nbE, $nbW );
		commit_trans();
	}
    
    
    
    // Facture
    $sqlcmd = "INSERT INTO temp.p_rsf_total( ";
    $sqlcmd = $sqlcmd . "finess, no_rss, code_pec, rang_beneficiaire, regime, nature_pec,  ";
    $sqlcmd = $sqlcmd . "justificatif_exo, no_facture, code_regularisation, base_remboursement,  ";
    $sqlcmd = $sqlcmd . "sejour_facture, sejour_remboursable, honoraires_factures, honoraires_remboursable,  ";
    $sqlcmd = $sqlcmd . "t2a_facture, dmi_facture, phc_facture, participation_assure_avant_oc,  ";
    $sqlcmd = $sqlcmd . "sejour_remboursable_2, honoraires_remboursable_2, montant_dmi_ghs2006,  ";
    $sqlcmd = $sqlcmd . "forfait_facture,  ";
    $sqlcmd = $sqlcmd . "nb_exh, ca_exh, nb_exb, ca_exb, nb_ghs, ca_ghs, taux_remboursement, regime_id, exoneration_tm_id, nature_pec_id, code_pec_id, rss_id, nb_ghsmin) ";
    $sqlcmd = $sqlcmd . "SELECT  ";
    $sqlcmd = $sqlcmd . "finess, no_rss, '1', '', '01', '10', '', '', '', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 0, 0, oid, 0   ";
    $sqlcmd = $sqlcmd . "FROM temp.p_rss ";
    $sqlcmd = $sqlcmd . "WHERE import_id = $import_id ";
    $sqlcmd = $sqlcmd . "AND oid NOT IN (SELECT rss_id FROM temp.p_rsf_total)";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    
    commit_trans();
    
    $sqlcmd = "UPDATE temp.p_rsf_total 
            SET base_remboursement = COALESCE(subview.base_remboursement,0)
            FROM temp.p_rss 
            LEFT JOIN (
                SELECT rss_id, 
                SUM(p_rsf_detail.base_remboursement) as base_remboursement 
                FROM temp.p_rsf_detail 
                WHERE p_rsf_detail.est_ligne_rss = '1' 
                GROUP BY rss_id) subview ON p_rss.oid = subview.rss_id
            WHERE import_id = $import_id AND
                p_rsf_total.rss_id = p_rss.oid AND  
                p_rss.ghm_id > 0 AND
                (
                    p_rsf_total.base_remboursement IS DISTINCT FROM  COALESCE(subview.base_remboursement,0)
                )";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    
    commit_trans();
    
    // Si fichier ValoSEJ importé, valorisation selon VALOSEJ
    if ($ENV_TYPEETS != "1") {
        generation_valosej();
    //    return;
    }
    
    analyse_table_temp("p_rsf_total");
    analyse_table_temp("p_rsf_detail");
    
    logInfoMsg("FIN VALORISATION GHS. $nbE erreurs.");
    
}


/*
 * Fichier .ano correspond au vidhospo anonymisé
 * Insertion dans la table p_vidhosp
 */
function generation_ano_vidhosp() {

    global $import_id;
    global $file_ANO;
    global $file_exists_ANO;

    if (!$file_exists_ANO) {
        logWarnMsg("Le fichier ANO (OUT) n'existe pas, pas de génération ANO");
        return;
    }

    logInfoMsg("GENERATION ANO");

    begin_trans();
    


    $rssadms_array = array();

    // Génération
    $nb = 0;
    $nbW = 0;
    $nbE = 0;
    $no_ligne = 0;
    $rss_id = 0;

    $handle = @fopen($file_ANO, "r");
    if ($handle) {
        while (!feof($handle)) {
            $buffer = fgets($handle, 99999);

            $no_ligne++;
            if (trim($buffer) !== "" && $no_ligne < 100000000000 ) {

                $nb++;

                $BUF_record = read_ano_line($buffer);


                if ($BUF_record["ok"] === true) {

                    if ($BUF_record["type_enregistrement"] === "ANO") {

                        $rss_id = 0;
                        $no_rss = 0;

                        $no_rsa = get_num($BUF_record["no_rsa"]);

                        $code_pec = $BUF_record["code_pec"];    // deprecated, remplacé par code_pec_id
                        $valideCodesPec = array("0", "1", "2", "3", "X");
                        if (!in_array($code_pec, $valideCodesPec)) {
                            $code_pec = "1";
                        }
                        $code_pec_id = get_pec($code_pec);

                        $nature_pec = $BUF_record["nature_assurance"];  // deprecated, remplacé par regime_id
                        if (! controle_check_num($nature_pec,2, false,$none,$none)) {
                            $nature_pec = "10";
                        }
                        $nature_pec_id = get_nature_pec($nature_pec);
                        $taux_remboursement = get_num($BUF_record["taux_remboursement_c"]) / 100;
                        $hospit_nouveau_ne = $BUF_record["hospit_nouveau_ne"];

                        $matricule_assure = $BUF_record["immatriculation_assure"] ;
                        $cle_matricule_assure = $BUF_record["cle_immatriculation_assure"] ;
                        $regime = $BUF_record["grand_regime"];  // deprecated, remplacé par regime_id
                        $regime_id = get_regime($BUF_record["grand_regime"]);
                        if (controle_check_date($BUF_record["date_naissance"],$none,$none, true)) {
                            $date_naissance = sqlDate($BUF_record["date_naissance"]);
                        } else {
                            $date_naissance = default_birth_date($BUF_record["date_naissance"]);
                        }
                        $sexe = $BUF_record["sexe"];
                        $no_sejour_administratif = get_charAsNum($BUF_record["no_sejour_administratif"]);
                        $justificatif_exo = $BUF_record["justificatif_exo"];    // deprecated, remplacé par exoneration_tm_id
                        $exoneration_tm_id = get_exoneration_tm($BUF_record["justificatif_exo"]);
                        $code_pec_fj = $BUF_record["code_pec_fj"];  // deprecated, remplacé par code_pec_fj_id
                        $code_pec_fj_id = get_pec_fj($BUF_record["code_pec_fj"]);
                        $type_contrat_oc = $BUF_record["type_contrat_oc"];  // deprecated, remplacé par type_contrat_oc_id
                        $type_contrat_oc_id = get_type_contrat_oc($BUF_record["type_contrat_oc"]);
                        $facturation_18euros = $BUF_record["facturation_18euros"];  // deprecated, remplacé par facturation_18euros_id
                        $facturation_18euros_id = get_facturation_18euros($BUF_record["facturation_18euros"]);
                        $nombre_venues = get_num($BUF_record["nombre_venues"]);
                        $montant_tm = get_num($BUF_record["montant_tm"]) / 100;
                        $montant_fj = get_num($BUF_record["montant_fj"]) / 100;
                        $montant_remboursable_amo = get_num($BUF_record["total_remboursable_amo"]) / 100;
                        $montant_parcours_soins = get_num($BUF_record["montant_parcours_soins"]);
                        $base_remboursement = get_num($BUF_record["base_remboursement_c"]) / 100;
                        $motif_non_facturation_id = get_motif_non_facturation($BUF_record["motif_non_facturation"]);
                        $cmu = $BUF_record["cmu"];
                        $prelevement_organe = $BUF_record["prelevement_organe"];
                        $montant_remboursable_amc = get_num($BUF_record["total_remboursable_amc"]) / 100;
                        $no_anonyme = $BUF_record["no_anonyme"];

                        // Nouveautés ANO_HOSP 2014, format V009
                        $code_participation_assure = $BUF_record["code_participation_assure"];
                        $rang_naissance = $BUF_record["rang_naissance"];
                        $rang_beneficiaire = $BUF_record["rang_beneficiaire"];
                        $no_entree = $BUF_record["no_entree"];
                        $no_caisse_gestionnaire = $BUF_record["no_caisse_gestionnaire"];
                        $no_centre_gestionnaire = $BUF_record["no_centre_gestionnaire"];
                        $code_gestion = $BUF_record["code_gestion"];
                        $confirmation_pec = $BUF_record["confirmation_pec"];
                        $no_at_date_adc = $BUF_record["no_at_date_adc"];
                        $no_organisme_complementaire = $BUF_record["no_organisme_complementaire"];

                        $finess = $BUF_record["finess"];
                        $no_format = $BUF_record["no_format"];
                        $no_format_vidhosp = $BUF_record["no_format_vidhosp"];
                        $mois_sortie = get_num($BUF_record["mois_sortie"]);
                        $annee_sortie = get_num($BUF_record["annee_sortie"]);
                        $no_anonyme_individuel = $BUF_record["no_anonyme_individuel"];
                        $no_sejour = $BUF_record["no_sejour"];
                        $delai_date_entree = $BUF_record["delai_date_entree"];
                        $date_entree_sejour_pmsi = get_date_or_null($BUF_record["date_entree_sejour_pmsi"]);
                        $date_sortie_sejour_pmsi = get_date_or_null($BUF_record["date_sortie_sejour_pmsi"]);
                        $no_anonyme_mere_enfant = $BUF_record["no_anonyme_mere_enfant"];
                        $no_chainage_mere_enfant = $BUF_record["no_chainage_mere_enfant"];
                        $identifiant_anonyme_hospit = $BUF_record["identifiant_anonyme_hospit"];
                        $id_first_hospit = $BUF_record["id_first_hospit"];
                        $nature_piece_justificative = $BUF_record["nature_piece_justificative"];
                        $date_pec = get_date_or_null($BUF_record["date_pec"]);
                        $date_debut_pec = get_date_or_null($BUF_record["date_debut_pec"]);
                        $delivre_par = $BUF_record["delivre_par"];
                        $regime_assure = $BUF_record["regime_assure"];
                        $top_eclatement_flux_etab = $BUF_record["top_eclatement_flux_etab"];
                        $date_entree = get_date_or_null($BUF_record["date_entree"]);
                        $date_sortie = ($BUF_record["date_sortie"] == "00000000") ? get_date_or_null("20991231") : get_date_or_null($BUF_record["date_sortie"]);
                        $montant_total_sejour_patient = get_num($BUF_record["montant_total_sejour_patient"]);
                        $nb_rejet_amo = get_num($BUF_record["nb_rejet_amo"]);
                        $date_facture_amo = get_date_or_null($BUF_record["date_facture_amo"]);
                        $date_facture_amc = get_date_or_null($BUF_record["date_facture_amc"]);
                        $date_facture_patient = get_date_or_null($BUF_record["date_facture_patient"]);
                        $date_paiement_amo = get_date_or_null($BUF_record["date_paiement_amo"]);
                        $date_paiement_amc = get_date_or_null($BUF_record["date_paiement_amc"]);
                        $date_paiement_patient = get_date_or_null($BUF_record["date_paiement_patient"]);
                        $statut_ft_amo = $BUF_record["statut_ft_amo"];
                        $statut_ft_amc = $BUF_record["statut_ft_amc"];
                        $statut_ft_patient = $BUF_record["statut_ft_patient"];
                        $pays_amo = $BUF_record["pays_amo"];
                        $ipp_anonymise = $BUF_record["ipp_anonymise"];
                        $ins_anonymise = $BUF_record["ins_anonymise"];

                        $crc_article_51 = $BUF_record["crc_article_51"];
                        $crc_base_remboursement_c = $BUF_record["crc_base_remboursement_c"];
                        $crc_cmu = $BUF_record["crc_cmu"];
                        $crc_code_gestion = $BUF_record["crc_code_gestion"];
                        $crc_code_participation_assure = $BUF_record["crc_code_participation_assure"];
                        $crc_code_pec = $BUF_record["crc_code_pec"];
                        $crc_code_pec_fj = $BUF_record["crc_code_pec_fj"];
                        $crc_coherence_date_naissance = $BUF_record["crc_coherence_date_naissance"];
                        $crc_coherence_sexe = $BUF_record["crc_coherence_sexe"];
                        $crc_confirmation_pec = $BUF_record["crc_confirmation_pec"];
                        $crc_date_debut_pec = $BUF_record["crc_date_debut_pec"];
                        $crc_date_entree = $BUF_record["crc_date_entree"];
                        $crc_date_facture_amc = $BUF_record["crc_date_facture_amc"];
                        $crc_date_facture_amo = $BUF_record["crc_date_facture_amo"];
                        $crc_date_facture_patient = $BUF_record["crc_date_facture_patient"];
                        $crc_date_hospitalisation = $BUF_record["crc_date_hospitalisation"];
                        $crc_date_naissance = $BUF_record["crc_date_naissance"];
                        $crc_date_paiement_amc = $BUF_record["crc_date_paiement_amc"];
                        $crc_date_paiement_amo = $BUF_record["crc_date_paiement_amo"];
                        $crc_date_paiement_patient = $BUF_record["crc_date_paiement_patient"];
                        $crc_date_pec = $BUF_record["crc_date_pec"];
                        $crc_date_reference = $BUF_record["crc_date_reference"];
                        $crc_date_sortie = $BUF_record["crc_date_sortie"];
                        $crc_delivre_par = $BUF_record["crc_delivre_par"];
                        $crc_facturation_18euros = $BUF_record["crc_facturation_18euros"];
                        $crc_finess = $BUF_record["crc_finess"];
                        $crc_fusion_anohosp_hosppmsi = $BUF_record["crc_fusion_anohosp_hosppmsi"];
                        $crc_fusion_anohosp_pmsi = $BUF_record["crc_fusion_anohosp_pmsi"];
                        $crc_grand_regime = $BUF_record["crc_grand_regime"];
                        $crc_hospit_nouveau_ne = $BUF_record["crc_hospit_nouveau_ne"];
                        $crc_id_first_hospit = $BUF_record["crc_id_first_hospit"];
                        $crc_immatriculation_assure = $BUF_record["crc_immatriculation_assure"];
                        $crc_immatriculation_indiv = $BUF_record["crc_immatriculation_indiv"];
                        $crc_identifiant_national_sante = $BUF_record["crc_identifiant_national_sante"];
                        $crc_justificatif_exo = $BUF_record["crc_justificatif_exo"];
                        $crc_montant_fj = $BUF_record["crc_montant_fj"];
                        $crc_montant_parcours_soins = $BUF_record["crc_montant_parcours_soins"];
                        $crc_montant_tm = $BUF_record["crc_montant_tm"];
                        $crc_montant_total_sejour_patient = $BUF_record["crc_montant_total_sejour_patient"];
                        $crc_motif_non_facturation = $BUF_record["crc_motif_non_facturation"];
                        $crc_nature_assurance = $BUF_record["crc_nature_assurance"];
                        $crc_nature_piece_justificative = $BUF_record["crc_nature_piece_justificative"];
                        $crc_no_anonyme_mere_enfant = $BUF_record["crc_no_anonyme_mere_enfant"];
                        $crc_no_at_date_adc = $BUF_record["crc_no_at_date_adc"];
                        $crc_no_caisse_gestionnaire = $BUF_record["crc_no_caisse_gestionnaire"];
                        $crc_no_centre_gestionnaire = $BUF_record["crc_no_centre_gestionnaire"];
                        $crc_no_entree = $BUF_record["crc_no_entree"];
                        $crc_no_identification_patient = $BUF_record["crc_no_identification_patient"];
                        $crc_no_organisme_complementaire = $BUF_record["crc_no_organisme_complementaire"];
                        $crc_no_sejour_administratif = $BUF_record["crc_no_sejour_administratif"];
                        $crc_nombre_venues = $BUF_record["crc_nombre_venues"];
                        $crc_pays_amo = $BUF_record["crc_pays_amo"];
                        $crc_prelevement_organe = $BUF_record["crc_prelevement_organe"];
                        $crc_rang_beneficiaire = $BUF_record["crc_rang_beneficiaire"];
                        $crc_rang_naissance = $BUF_record["crc_rang_naissance"];
                        $crc_regime_assure = $BUF_record["crc_regime_assure"];
                        $crc_rejet_amo = $BUF_record["crc_rejet_amo"];
                        $crc_sexe = $BUF_record["crc_sexe"];
                        $crc_statut_ft_amc = $BUF_record["crc_statut_ft_amc"];
                        $crc_statut_ft_amo = $BUF_record["crc_statut_ft_amo"];
                        $crc_statut_ft_patient = $BUF_record["crc_statut_ft_patient"];
                        $crc_taux_remboursement_c = $BUF_record["crc_taux_remboursement_c"];
                        $crc_top_eclatement_flux_etab = $BUF_record["crc_top_eclatement_flux_etab"];
                        $crc_total_remboursable_amc = $BUF_record["crc_total_remboursable_amc"];
                        $crc_total_remboursable_amo = $BUF_record["crc_total_remboursable_amo"];
                        $crc_type_contrat_oc = $BUF_record["crc_type_contrat_oc"];

                            // DMT depuis mars 2025
                        $nbDmt = $BUF_record["nb_dmt"];
                        $crc_nb_dmt = $BUF_record["crc_nb_dmt"];

                        $no_rss = 0;

                        if ($no_rsa > 0) {

                            $sqlcmd = "INSERT INTO temp.p_vidhosp(
                                    no_rsa, rss_id, matricule_assure, cle_matricule_assure, regime, date_naissance, 
                                    sexe, no_sejour_administratif, justificatif_exo, code_pec_fj, 
                                    nature_pec, type_contrat_oc, code_pec, facturation_18euros, 
                                    nombre_venues, montant_tm, montant_fj, montant_remboursable_amo, 
                                    montant_parcours_soins, base_remboursement, taux_remboursement,
                                    cmu, hospit_nouveau_ne,
                                    prelevement_organe, montant_remboursable_amc, regime_id, exoneration_tm_id, nature_pec_id, 
                                    code_pec_id, motif_non_facturation_id, code_pec_fj_id, type_contrat_oc_id, facturation_18euros_id,
                                    no_anonyme, ipp_anonymise, ins_anonymise,
                                    code_participation_assure, rang_naissance, rang_beneficiaire,
                                    no_entree, no_caisse_gestionnaire, no_centre_gestionnaire, code_gestion,
                                    confirmation_pec, no_at_date_adc, no_organisme_complementaire,
                                    finess, no_format, no_format_vidhosp, mois_sortie, annee_sortie, 
                                    no_anonyme_individuel, no_sejour, date_entree_sejour_pmsi, date_sortie_sejour_pmsi, no_anonyme_mere_enfant, 
                                    no_chainage_mere_enfant, identifiant_anonyme_hospit, id_first_hospit, nature_piece_justificative, date_debut_pec, 
                                    date_pec, delivre_par, regime_assure, top_eclatement_flux_etab, date_entree, date_sortie, 
                                    montant_total_sejour_patient, nb_rejet_amo, date_facture_amo, date_facture_amc, 
                                    date_facture_patient, date_paiement_amo, date_paiement_amc, date_paiement_patient, statut_ft_amo, 
                                    statut_ft_amc, statut_ft_patient, pays_amo,delai_date_entree, nb_dmt, import_id
                                    )
                                VALUES (
                                    $no_rsa, $rss_id, '$matricule_assure', '$cle_matricule_assure', '$regime', '$date_naissance', 
                                    '$sexe', '$no_sejour_administratif', '$justificatif_exo', '$code_pec_fj', 
                                    '$nature_pec', '$type_contrat_oc', '$code_pec', '$facturation_18euros', 
                                    $nombre_venues, $montant_tm, $montant_fj, $montant_remboursable_amo, 
                                    $montant_parcours_soins, $base_remboursement, $taux_remboursement,
                                    '$cmu', '$hospit_nouveau_ne',
                                    '$prelevement_organe', $montant_remboursable_amc, $regime_id, $exoneration_tm_id, $nature_pec_id, 
                                    $code_pec_id, $motif_non_facturation_id, $code_pec_fj_id, $type_contrat_oc_id, $facturation_18euros_id,
                                    '$no_anonyme', '$ipp_anonymise', '$ins_anonymise',
                                    '$code_participation_assure', '$rang_naissance', '$rang_beneficiaire',
                                    '$no_entree', '$no_caisse_gestionnaire', '$no_centre_gestionnaire', '$code_gestion',
                                    '$confirmation_pec', '$no_at_date_adc', '$no_organisme_complementaire',
                                    '$finess', '$no_format', '$no_format_vidhosp', $mois_sortie, $annee_sortie, 
                                    '$no_anonyme_individuel', '$no_sejour', $date_entree_sejour_pmsi, $date_sortie_sejour_pmsi, '$no_anonyme_mere_enfant', 
                                    '$no_chainage_mere_enfant', '$identifiant_anonyme_hospit', '$id_first_hospit', '$nature_piece_justificative', $date_debut_pec, 
                                    $date_pec, '$delivre_par', '$regime_assure', '$top_eclatement_flux_etab', $date_entree, $date_sortie, 
                                    $montant_total_sejour_patient, $nb_rejet_amo, $date_facture_amo, $date_facture_amc, 
                                    $date_facture_patient, $date_paiement_amo, $date_paiement_amc, $date_paiement_patient, '$statut_ft_amo', 
                                    '$statut_ft_amc', '$statut_ft_patient', '$pays_amo', '$delai_date_entree', $nbDmt, $import_id)";
                            $toResult = execute_sql($sqlcmd, $nbE, $nbW );

                            $sqlcmd = "INSERT INTO temp.p_vidhosp_crc(
                                            rss_id, no_rsa, 
                                            crc_article_51, crc_base_remboursement_c, crc_cmu, crc_code_gestion, crc_code_participation_assure, crc_code_pec, 
                                            crc_code_pec_fj, crc_coherence_date_naissance, crc_coherence_sexe, crc_confirmation_pec, crc_date_debut_pec, crc_date_entree, 
                                            crc_date_facture_amc, crc_date_facture_amo, crc_date_facture_patient, crc_date_hospitalisation, crc_date_naissance, 
                                            crc_date_paiement_amc, crc_date_paiement_amo, crc_date_paiement_patient, crc_date_pec, crc_date_reference, 
                                            crc_date_sortie, crc_delivre_par, crc_facturation_18euros, crc_finess, crc_fusion_anohosp_hosppmsi, 
                                            crc_fusion_anohosp_pmsi, crc_grand_regime, crc_hospit_nouveau_ne, crc_id_first_hospit, crc_identifiant_national_sante, crc_immatriculation_assure, 
                                            crc_immatriculation_indiv, crc_justificatif_exo, crc_montant_fj, crc_montant_parcours_soins, crc_montant_tm, 
                                            crc_montant_total_sejour_patient, crc_motif_non_facturation, crc_nature_assurance, crc_nature_piece_justificative, crc_no_anonyme_mere_enfant, 
                                            crc_no_at_date_adc, crc_no_caisse_gestionnaire, crc_no_centre_gestionnaire, crc_no_entree, crc_no_identification_patient, crc_no_organisme_complementaire, 
                                            crc_no_sejour_administratif, crc_nombre_venues, crc_pays_amo, crc_prelevement_organe, crc_rang_beneficiaire, 
                                            crc_rang_naissance, crc_regime_assure, crc_rejet_amo, crc_sexe, crc_statut_ft_amc, 
                                            crc_statut_ft_amo, crc_statut_ft_patient, crc_taux_remboursement_c, crc_top_eclatement_flux_etab, crc_total_remboursable_amc, 
                                            crc_total_remboursable_amo, crc_type_contrat_oc, crc_nb_dmt, crc_import_id)
                                VALUES (
                                    $rss_id, $no_rsa,
                                    '$crc_article_51', '$crc_base_remboursement_c', '$crc_cmu', '$crc_code_gestion', '$crc_code_participation_assure', '$crc_code_pec', 
                                    '$crc_code_pec_fj', '$crc_coherence_date_naissance', '$crc_coherence_sexe', '$crc_confirmation_pec', '$crc_date_debut_pec', '$crc_date_entree', 
                                    '$crc_date_facture_amc', '$crc_date_facture_amo', '$crc_date_facture_patient', '$crc_date_hospitalisation', '$crc_date_naissance', 
                                    '$crc_date_paiement_amc', '$crc_date_paiement_amo', '$crc_date_paiement_patient', '$crc_date_pec', '$crc_date_reference', 
                                    '$crc_date_sortie', '$crc_delivre_par', '$crc_facturation_18euros', '$crc_finess', '$crc_fusion_anohosp_hosppmsi', 
                                    '$crc_fusion_anohosp_pmsi', '$crc_grand_regime', '$crc_hospit_nouveau_ne', '$crc_id_first_hospit', '$crc_identifiant_national_sante', '$crc_immatriculation_assure', 
                                    '$crc_immatriculation_indiv', '$crc_justificatif_exo', '$crc_montant_fj', '$crc_montant_parcours_soins', '$crc_montant_tm', 
                                    '$crc_montant_total_sejour_patient', '$crc_motif_non_facturation', '$crc_nature_assurance', '$crc_nature_piece_justificative', '$crc_no_anonyme_mere_enfant', 
                                    '$crc_no_at_date_adc', '$crc_no_caisse_gestionnaire', '$crc_no_centre_gestionnaire', '$crc_no_entree', '$crc_no_identification_patient', '$crc_no_organisme_complementaire', 
                                    '$crc_no_sejour_administratif', '$crc_nombre_venues', '$crc_pays_amo', '$crc_prelevement_organe', '$crc_rang_beneficiaire', 
                                    '$crc_rang_naissance', '$crc_regime_assure', '$crc_rejet_amo', '$crc_sexe', '$crc_statut_ft_amc', 
                                    '$crc_statut_ft_amo', '$crc_statut_ft_patient', '$crc_taux_remboursement_c', '$crc_top_eclatement_flux_etab', '$crc_total_remboursable_amc', 
                                    '$crc_total_remboursable_amo', '$crc_type_contrat_oc', '$crc_nb_dmt', $import_id)";
                            $toResult = execute_sql($sqlcmd, $nbE, $nbW );

                            if ($nbDmt > 0) {
                                for ($i = 0; $i < $nbDmt ; $i++){
                                    // crc
                                    $crc_dmt_code = $BUF_record["crc_dmt_code"][$i];
                                    $crc_dmt_mode_traitement = $BUF_record["crc_dmt_mode_traitement"][$i];
                                    $crc_dmt_date_debut_sejour = $BUF_record["crc_dmt_date_debut_sejour"][$i];
                                    $crc_dmt_date_fin_sejour = $BUF_record["crc_dmt_date_fin_sejour"][$i];
                                    $crc_dmt_quantite = $BUF_record["crc_dmt_quantite"][$i];
                                    $crc_dmt_prix_unitaire = $BUF_record["crc_dmt_prix_unitaire"][$i];
                                    $crc_dmt_base_remboursement = $BUF_record["crc_dmt_base_remboursement"][$i];
                                    $crc_dmt_taux_applicable_prestation = $BUF_record["crc_dmt_taux_applicable_prestation"][$i];
                                    $crc_dmt_montant_remboursable = $BUF_record["crc_dmt_montant_remboursable"][$i];

                                    // DMT
                                    $dmt_code = $BUF_record["dmt_code"][$i];
                                    $dmt_mode_traitement = $BUF_record["dmt_mode_traitement"][$i];
                                    $dmt_date_debut_sejour = get_date_or_null($BUF_record["dmt_date_debut_sejour"][$i]);
                                    $dmt_date_fin_sejour = get_date_or_null($BUF_record["dmt_date_fin_sejour"][$i]);
                                    $dmt_quantite = $BUF_record["dmt_quantite"][$i];
                                    $dmt_prix_unitaire = $BUF_record["dmt_prix_unitaire"][$i];
                                    $dmt_base_remboursement = $BUF_record["dmt_base_remboursement"][$i];
                                    $dmt_taux_applicable_prestation = $BUF_record["dmt_taux_applicable_prestation"][$i];
                                    $dmt_montant_remboursable = $BUF_record["dmt_montant_remboursable"][$i];

                                    // Code retour contrôle "DMT n°NbDNT cohérence DMT/MT"
                                    $crc_dmt_coherence_dmt_mt = $BUF_record["crc_coherence_dmt_mt"][$i];

                                    if ($dmt_code === "XXX"){
                                        continue;
                                    }

                                        $sqlcmd = <<<SQL
                                    INSERT INTO temp.p_vidhosp_dmt(
                                        base_remboursement, date_debut, date_fin, dmt_code, mode_traitement, montant_remboursable,
                                        import_id, prix_unitaire, quantite, rss_id, taux_prestation
                                    )
                                    VALUES (
                                        $dmt_base_remboursement, $dmt_date_debut_sejour, $dmt_date_fin_sejour, '$dmt_code', '$dmt_mode_traitement', $dmt_montant_remboursable,
                                        $import_id, $dmt_prix_unitaire, $dmt_quantite, $rss_id, $dmt_taux_applicable_prestation
                                    );
SQL;
                                    execute_sql($sqlcmd, $nbE, $nbW );


                                    $sqlcmd = <<<SQL
                                        INSERT INTO temp.p_vidhosp_dmt_crc(
                                            crc_base_remboursement, crc_coherence_dmt_mt, crc_date_debut, crc_date_fin,
                                            crc_dmt_code, crc_mode_traitement, crc_montant_remboursable,
                                            crc_prix_unitaire, crc_quantite, crc_taux_prestation,
                                            import_id, rss_id
                                        )
                                        VALUES (
                                            '$crc_dmt_base_remboursement', '$crc_dmt_coherence_dmt_mt', '$crc_dmt_date_debut_sejour', '$crc_dmt_date_fin_sejour',
                                            '$crc_dmt_code', '$crc_dmt_mode_traitement', '$crc_dmt_montant_remboursable',
                                            '$crc_dmt_prix_unitaire', '$crc_dmt_quantite', '$crc_dmt_taux_applicable_prestation',
                                            $import_id, $rss_id
                                        );
SQL;
                                    execute_sql($sqlcmd, $nbE, $nbW );
                                }

                            }
                        }


                    }

                }



            }

        }

        fclose($handle);

    }

    commit_trans();

    // rss_id pour vidhosp
    $sqlcmd = "UPDATE temp.p_vidhosp SET rss_id = p_rsa.rss_id
        FROM temp.p_rsa, temp.p_rss
        WHERE p_rsa.no_rsa = p_vidhosp.no_rsa
        AND p_rsa.rss_id = p_rss.oid
        AND p_rss.import_id = $import_id
        AND (p_vidhosp.rss_id = 0)";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();

    $sqlcmd = "
        UPDATE temp.p_vidhosp_crc SET 
            rss_id = p_vidhosp.rss_id
        FROM 
            temp.p_vidhosp
        WHERE 1=1
            AND p_vidhosp_crc.no_rsa = p_vidhosp.no_rsa
            AND p_vidhosp_crc.rss_id = 0";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();

    logInfoMsg("FIN GENERATION VIDHOSP. $nb lus, $nbW écris, $nbE erreurs.");

    
}


function generation_ctl() {

    global $file_CTL;
    global $file_exists_CTL;

    if (! $file_exists_CTL) {
        return;
    }

    logInfoMsg("GENERATION CTL_MT2A");
    
    
    begin_trans();
    

    $nb = 0;
    $nbW = 0;
    $nbE = 0;
    
    $handle = @fopen($file_CTL, "r");
    if ($handle) {
        while (!feof($handle)) {
            $buffer = fgets($handle, 99999);
            
            $no_ligne++;
            if (trim($buffer) != "" && $no_ligne < 100000000000 ) {
            
                $nb++;
                
                $BUF_record = read_ctl_line($buffer);
                
                
                if ($BUF_record["ok"] == TRUE) {

                    $rss_id = 0;
                    $no_rss = get_numrss($BUF_record["no_rss"]);
                    $no_sejour_administratif = get_charAsNum($BUF_record["no_sejour_administratif"]);
                    $erreur_genrsa = $BUF_record["erreur_genrsa"];
                    
                    $rss_id = get_rss($no_rss) + 0;

                    if ($no_rss > 0 && $rss_id > 0) {

                        $sqlcmd = "INSERT INTO temp.p_ctl_mt2a(
                                rss_id, no_rss, no_sejour_administratif, erreur_genrsa)
                            VALUES (
                                $rss_id, $no_rss, '$no_sejour_administratif', '$erreur_genrsa')";
                        $toResult = execute_sql($sqlcmd, $nbE, $nbW );

                    }

                }
                
                

            }
        
        }
        
        fclose($handle);
    
    }
    
    commit_trans();
    
    logInfoMsg("FIN GENERATION CTL_MT2A. $nb lus, $nbW écris, $nbE erreurs.");

    
}


function generation_rum_post_traitements() {

    global $import_id;
    global $omitComplements;
    global $file_exists_RSSMED;


    logInfoMsg("TRAITEMENTS COMPLEMENTAIRES RUM");
    
    begin_trans();
    
    enable_index("i_rss_3");
    enable_index("i_rss_4");
    enable_index("i_rss_5");
    enable_index("i_rss_8");
    enable_index("i_rss_11");
    enable_index("i_rss_12");
    enable_index("i_rss_13");
    enable_index("i_rss_14");
    enable_index("i_rss_16");
    enable_index("i_rss_17");
    enable_index("i_rss_18");
    enable_index("i_rss_19");
    
    enable_index("i_identites_3");
    
    enable_index("i_rss_rum_6");
    enable_index("i_rss_rum_12");
    enable_index("i_rss_rum_13");
    
    enable_index("i_rss_diagnostics_2");
    enable_index("i_rss_diagnostics_3");
    enable_index("i_rss_diagnostics_6");
    enable_index("i_rss_diagnostics_7");
    
    enable_index("i_rsf_total_3");
    
    enable_index("i_rsf_detail_2");
    enable_index("i_rsf_detail_5");
    
    enable_index("i_rss_actes_2");
    enable_index("i_rss_actes_4");
    enable_index("i_rss_actes_5");
    enable_index("i_rss_actes_8");
    enable_index("i_rss_actes_9");

    
    analyse_tables();
    
    $nbE = 0;
	
	logInfoMsg("CCAM Descriptive");

    $sqlcmd = "UPDATE pmsi.t_actes SET
				racine_id = t_actes_7.oid,
				racine_code = t_actes_7.code,
				racine_texte = t_actes_7.texte
			FROM pmsi.t_actes t_actes_7 
			WHERE substr(t_actes.code,1,7) = t_actes_7.code AND
				length(t_actes.code) >= 7 AND
				(
				t_actes.racine_id IS DISTINCT FROM t_actes_7.oid OR
				t_actes.racine_code IS DISTINCT FROM t_actes_7.code OR
				t_actes.racine_texte IS DISTINCT FROM t_actes_7.texte
				)";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();

    $sqlcmd = "UPDATE temp.p_rss_actes
				SET acte_id = racine_id
				FROM pmsi.t_actes
				WHERE acte_ccam_descriptif_id = t_actes.oid AND
					racine_id <> p_rss_actes.acte_id
				;";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();

	// Cette requete ne fonctionne pas et je ne sais pas à quoi elle sert (ELA 05/02/2021)
	//$sqlcmd = "UPDATE temp.p_rss_actes
	//			SET acte_id = acte_ccam_descriptif_id
	//			FROM pmsi.t_actes
	//			WHERE acte_ccam_descriptif_id <> t_actes.oid AND date_acte >= '2020-01-01'
	//			;";
    //$toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    //commit_trans();
	
	// Suppression des lignes d'actes en double car provenant des RSF et aussi (en mode descriptif) des RSS
	$sqlcmd = "DELETE
		FROM temp.p_rss_actes
		USING
		(
		SELECT 
			rss_id, no_rss, date_acte, racine_id, activite_ccam, MAX(CASE WHEN racine_id = t_actes.oid THEN acte_ccam_descriptif_id ELSE 0 END) AS acte_ccam_descriptif_id,
			SUM(CASE WHEN racine_id <> t_actes.oid THEN 1 ELSE 0 END),
			SUM(CASE WHEN racine_id = t_actes.oid THEN 1 ELSE 0 END)
		FROM temp.p_rss_actes
		JOIN pmsi.t_actes ON p_rss_actes.acte_ccam_descriptif_id = t_actes.oid
		GROUP BY 1,2,3,4,5
		HAVING SUM(CASE WHEN racine_id <> t_actes.oid THEN 1 ELSE 0 END) > 0 AND
			SUM(CASE WHEN racine_id = t_actes.oid THEN 1 ELSE 0 END) > 0
		) subview
		WHERE p_rss_actes.rss_id = subview.rss_id AND
			p_rss_actes.date_acte = subview.date_acte AND
			p_rss_actes.acte_ccam_descriptif_id = subview.acte_ccam_descriptif_id AND
			p_rss_actes.activite_ccam = subview.activite_ccam";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
    
    
    
    
    
    // données complémentaires aspirateur
    //generation_donnees_complementaires("temp", "PMSICOMPLEMENTS");
    if ($omitComplements == false) { // ENLEVER LE OMMIT COMPLEMENT -> TOUJOURS LE JOUER
       generation_donnees_complementaires("temp", "PMSICOMPLEMENTS");
    }
    else {
        logInfoMsg("Omission du traitement des données complémentaires du prestataire PMSI");
    }
    
    logInfoMsg("Initialisation patients de l'année");
    
    $sqlcmd = "DROP TABLE IF EXISTS temp_pmsi_identites ;";
    $toResult = execute_sql($sqlcmd);
    commit_trans();

    $sqlcmd = "CREATE TEMP TABLE temp_pmsi_identites (finess character(9), nom character varying(255), prenom character varying(255), nomprenom character varying(255), date_naissance date, sexe character(1));";
    $toResult = execute_sql($sqlcmd);
    commit_trans();

    $sqlcmd = "INSERT INTO temp_pmsi_identites(finess, nom, prenom, nomprenom, date_naissance, sexe)
        SELECT DISTINCT p_rss.finess, p_identites.nom, p_identites.prenom, upper(translate(p_identites.nom || p_identites.prenom, ' -', '')) AS nomprenom, p_rss.date_naissance, p_rss.sexe
        FROM temp.p_rss, temp.p_identites 
        WHERE p_rss.oid = p_identites.rss_id AND (p_rss.patient_id IS NULL OR p_rss.patient_id = 0);";
    $toResult = execute_sql($sqlcmd);
    commit_trans();


    $sqlcmd = "INSERT INTO pmsi.p_patients (finess, nom, prenom, date_naissance, sexe)
    SELECT temp_pmsi_identites.finess, temp_pmsi_identites.nom, temp_pmsi_identites.prenom, temp_pmsi_identites.date_naissance, temp_pmsi_identites.sexe FROM temp_pmsi_identites 
    LEFT JOIN pmsi.p_patients ON (
        temp_pmsi_identites.nomprenom = upper(translate(p_patients.nom || p_patients.prenom, ' -', ''))
        AND temp_pmsi_identites.date_naissance = p_patients.date_naissance
        AND temp_pmsi_identites.sexe = p_patients.sexe)
    WHERE p_patients.nom IS NULL";
    $toResult = execute_sql($sqlcmd);
    commit_trans();
    
    $sqlcmd = "UPDATE pmsi.p_patients SET no_patient = 0 - nextval('pmsi.s_no_interne_patients'::regclass) WHERE no_patient = 0 OR no_patient IS NULL; ";
    $toResult = execute_sql($sqlcmd);
    
    commit_trans();
    
    $sqlcmd = "UPDATE temp.p_rss SET patient_id = p_patients.oid  
        FROM temp.p_identites, pmsi.p_patients  
        WHERE p_rss.oid = p_identites.rss_id 
        AND COALESCE(p_rss.patient_id,0) = 0 
        AND p_rss.date_naissance = p_patients.date_naissance 
        AND p_rss.sexe = p_patients.sexe 
        AND upper(translate(p_identites.nom || p_identites.prenom, ' -', '')) = upper(translate(p_patients.nom || p_patients.prenom, ' -', ''))  ";
    
    $toResult = execute_sql($sqlcmd);
    
    commit_trans();
    
    $sqlcmd = "UPDATE temp.p_rss SET patient_id = subview.new_id FROM  
            ( 
            SELECT  
            p_patients.oid AS old_id,  
            p_patients_nouveaux.oid as new_id  
            FROM pmsi.p_patients, pmsi.p_patients p_patients_nouveaux  
            WHERE p_patients.oid < p_patients_nouveaux.oid 
            AND upper(translate(p_patients.nom || p_patients.prenom, ' -', '')) = upper(translate(p_patients_nouveaux.nom || p_patients_nouveaux.prenom, ' -', '')) 
            AND p_patients.date_naissance = p_patients_nouveaux.date_naissance 
            AND p_patients.sexe = p_patients_nouveaux.sexe 
            ) subview  
            WHERE p_rss.patient_id = subview.old_id ";
    
    $toResult = execute_sql($sqlcmd);
    commit_trans();
    $toResult = execute_sql($sqlcmd);
    commit_trans();
    
    logInfoMsg("Calcul age");
    
    $sqlcmd = "UPDATE temp.p_rss SET age = trunc((date_entree::date - date_naissance::date) / 365.25,0)  ";
    $sqlcmd = $sqlcmd . "WHERE age <> trunc((date_entree::date - date_naissance::date) / 365.25,0) ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    
    commit_trans();
    
    
    $sqlcmd = "UPDATE temp.p_rss SET duree_sejour = 0  
        WHERE duree_sejour <> 0 AND ghm_id IN (SELECT oid FROM pmsi.t_ghm_c WHERE cmd_code = '28') ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    
    commit_trans();
	
	logInfoMsg("Suppression des RUM en double");
	$sqlcmd = "
		WITH doublons as (
			SELECT rss_id, no_rum FROM temp.p_rss_rum GROUP BY 1,2 HAVING count(*)  > 1
		)
		DELETE FROM temp.p_rss_rum
		USING doublons
		WHERE 1=1
			AND doublons.rss_id = p_rss_rum.rss_id
			AND doublons.no_rum = p_rss_rum.no_rum";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
	
    logInfoMsg("Initialisation unite medicale dans actes");

    $sqlcmd = "UPDATE temp.p_rss_actes SET
        no_rum = p_rss_rum.no_rum, 
        unite_medicale = p_rss_rum.unite_medicale, 
        unite_medicale_id = p_rss_rum.unite_medicale_id 
    FROM temp.p_rss_rum 
    WHERE p_rss_actes.no_rum = 0 AND
        p_rss_actes.rss_id = p_rss_rum.rss_id AND
        p_rss_actes.date_acte BETWEEN p_rss_rum.date_entree AND p_rss_rum.date_sortie;";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();


    $sqlcmd = "UPDATE temp.p_rss_actes 
    SET unite_medicale_id = p_rss_rum.unite_medicale_id 
    FROM temp.p_rss_rum 
    WHERE (p_rss_actes.unite_medicale_id = 0 OR p_rss_actes.unite_medicale_id IS NULL) AND 
        p_rss_actes.rss_id = p_rss_rum.rss_id AND 
        p_rss_actes.no_rum = p_rss_rum.no_rum AND
        p_rss_rum.unite_medicale_id <> 0;";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
    
    
    logInfoMsg("Initialisation unite medicale dans diagnostics");

    $sqlcmd = "UPDATE temp.p_rss_diagnostics SET unite_medicale_id = p_rss_rum.unite_medicale_id FROM ";
    $sqlcmd = $sqlcmd . "temp.p_rss_rum WHERE (p_rss_diagnostics.unite_medicale_id = 0 OR p_rss_diagnostics.unite_medicale_id IS NULL) ";
    $sqlcmd = $sqlcmd . "AND p_rss_diagnostics.rss_id = p_rss_rum.rss_id AND p_rss_diagnostics.no_rum = p_rss_rum.no_rum ;";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();

    
    logInfoMsg("Initialisation médecins bébé");
    $sqlcmd = "UPDATE temp.p_rss
            SET medecin_rss_id = p_rss_mere.medecin_rss_id
            FROM temp.p_rss p_rss_mere
            WHERE p_rss.rss_mere_id = p_rss_mere.oid AND
                p_rss.medecin_rss_id = 0";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    if ($file_exists_RSSMED) {
        logInfoMsg("Initialisation médecins rss");
        
        $sqlcmd = "UPDATE temp.p_rss ";
        $sqlcmd = $sqlcmd . "SET medecin_rss_id = ";
        $sqlcmd = $sqlcmd . "CASE WHEN "; 
        $sqlcmd = $sqlcmd . "(SELECT medecin_id FROM pmsi.v_rss_actes_1 WHERE activite_ccam <> '4' AND v_rss_actes_1.rss_id = p_rss.oid ORDER BY icr DESC LIMIT 1) > 0 ";
        $sqlcmd = $sqlcmd . "THEN (SELECT medecin_id FROM pmsi.v_rss_actes_1 WHERE activite_ccam <> '4' AND v_rss_actes_1.rss_id = p_rss.oid ORDER BY icr DESC LIMIT 1) ELSE p_rss.medecin_rss_id END ";
        $sqlcmd = $sqlcmd . "WHERE import_id = $import_id ";
        $sqlcmd = $sqlcmd . "AND (medecin_rss_id = 0 or medecin_rss_id IN (SELECT oid FROM pmsi.t_medecins WHERE code = '9999'))  ";
        
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );

        commit_trans();
    }
    
    logInfoMsg("Initialisation types d'autorisation");
    
    $sqlcmd = "INSERT INTO pmsi.t_types_autorisations (code, texte, texte_court) (SELECT DISTINCT type_autorisation, type_autorisation, type_autorisation FROM temp.p_rss_rum WHERE type_autorisation NOT IN (SELECT code FROM pmsi.t_types_autorisations)) ";
    
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    
    $sqlcmd = "INSERT INTO pmsi.t_types_autorisations (code, texte, texte_court) (SELECT DISTINCT t_unites_medicales.type_autorisation, t_unites_medicales.type_autorisation, t_unites_medicales.type_autorisation
                FROM temp.p_rss_rum JOIN pmsi.t_unites_medicales on t_unites_medicales.oid = p_rss_rum.unite_medicale_id WHERE t_unites_medicales.type_autorisation NOT IN (SELECT code FROM pmsi.t_types_autorisations)) ";
    
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    
    commit_trans();
    
    logInfoMsg("Initialisation RUM principal");
    
    //$dateDebutFG12 = '20100301';  Supprimer les Date FG12
    
    $sqlcmd = "UPDATE pmsi.t_unites_medicales SET type_autorisation = '' WHERE type_autorisation IS NULL";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    // Si GHM non renseigné depuis fichier IN, recherche dans fichier OUT
    $sqlcmd = "
        UPDATE temp.p_rss
        SET ghm_id = p_rsa.ghm_genrsa_id, ghs_id = p_rsa.ghs_genrsa_id
        FROM temp.p_rsa
        WHERE p_rsa.rss_id = p_rss.oid AND
            p_rss.ghm_id = 0 AND
            p_rsa.ghm_genrsa_id <> 0
    ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    // Si GHM GENRSA différent
    $sqlcmd = "
        UPDATE temp.p_rss
        SET ghm_id = ghm_genrsa_id
        FROM temp.p_rsa
        WHERE rss_id = p_rss.oid AND
            p_rss.ghm_id <> ghm_genrsa_id
    ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    // no_rum_principal depuis les RSA
    $sqlcmd = "
        UPDATE temp.p_rss
        SET no_rum_principal = p_rsa.no_rum_dp
        FROM temp.p_rsa
        WHERE p_rss.oid = p_rsa.rss_id AND
            no_rum_principal IS DISTINCT FROM p_rsa.no_rum_dp;
    ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();

    
    // diag principal sur RSS
    $sqlcmd = "UPDATE temp.p_rss SET ";
    $sqlcmd = $sqlcmd . "unite_medicale_principale_id = unite_medicale_id, ";
    $sqlcmd = $sqlcmd . "diagnostic_principal_id = p_rss_rum.diagnostic_principal_id, ";
    $sqlcmd = $sqlcmd . "diagnostic_relie_id = p_rss_rum.diagnostic_relie_id ";
    $sqlcmd = $sqlcmd . "FROM temp.p_rss_rum ";
    $sqlcmd = $sqlcmd . "WHERE p_rss.oid = p_rss_rum.rss_id  AND p_rss.no_rum_principal = p_rss_rum.no_rum AND p_rss.nb_rum > 1 ";
    $sqlcmd = $sqlcmd . "AND (unite_medicale_principale_id IS null OR unite_medicale_principale_id = 0)";
    
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    
    commit_trans();
    
    
    // dignostics principaux sur rum secondaire
    $sqlcmd = "UPDATE temp.p_rss_diagnostics SET type_diagnostic_rss = 'DA' FROM temp.p_rss ";
    $sqlcmd = $sqlcmd . "WHERE p_rss.oid = p_rss_diagnostics.rss_id ";
    $sqlcmd = $sqlcmd . "AND p_rss.no_rum_principal <> p_rss_diagnostics.no_rum  ";
    $sqlcmd = $sqlcmd . "AND p_rss.nb_rum > 1  ";
    $sqlcmd = $sqlcmd . "AND type_diagnostic_rss <> 'DA' AND type_diagnostic_rss <> 'DD'";
    
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    
    // Médecin par défaut 
    $sqlcmd = "UPDATE temp.p_rss
            SET medecin_rss_id = medecin_par_defaut_id 
            FROM pmsi.t_unites_medicales
            WHERE unite_medicale_principale_id = t_unites_medicales.oid AND
                medecin_rss_id = 0 AND
                COALESCE(medecin_par_defaut_id,0) <> 0;";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    
    
    
    
    
    // initialisation départements provenant du RSS
    $sqlcmd = "
        INSERT INTO base.t_departements (code, texte, texte_court) 
        SELECT 
            DISTINCT substr(code ,1, 2), 
            substr(code ,1, 2), 
            substr(code ,1, 2) 
        FROM base.t_codes_postaux 
        WHERE 
            substr(code ,1, 2) NOT IN ('97', '98') 
            AND substr(code ,1, 2) NOT IN (SELECT code FROM base.t_departements )
        ;
        
        INSERT INTO base.t_departements (code, texte, texte_court) 
        SELECT 
            DISTINCT substr(code ,1, 3), 
            substr(code ,1, 3), 
            substr(code ,1, 3) 
        FROM base.t_codes_postaux 
        WHERE 
            substr(code ,1, 2) IN ('97', '98') 
            AND substr(code ,1, 3) NOT IN (SELECT code FROM base.t_departements )
        ; ";
    $toResult = execute_sql($sqlcmd);
    
    commit_trans();

    // initialisation codes postaux  provenant du RSS
    logInfoMsg("Initialisation codes postaux");
    $sqlcmd = " 
        INSERT INTO base.t_codes_postaux (code, texte, texte_court, departement_id, code_geographique_pmsi, territoire_sante_id)
        SELECT 
            DISTINCT code_postal, 
            code_postal, 
            code_postal, 
            COALESCE((SELECT oid FROM base.t_departements WHERE code = substr(code_postal, 1 , 2)), 0), 
            substr(code_postal, 1 , 2) || '***', 
            COALESCE((SELECT t_territoires_sante.oid FROM base.t_territoires_sante JOIN base.t_regions ON t_regions.code || '*****' = t_territoires_sante.code JOIN base.t_departements ON t_departements.region_id = t_regions.oid WHERE t_departements.code = substr(code_postal, 1 , 2)), 0)
        FROM temp.p_rss
        WHERE 
            code_postal <> '' 
            AND code_postal NOT IN (SELECT code FROM base.t_codes_postaux )
            AND substr(code_postal, 1 , 2) NOT IN ('97', '98')
        ;
    
        INSERT INTO base.t_codes_postaux (code, texte, texte_court, departement_id, code_geographique_pmsi, territoire_sante_id)
        SELECT 
            DISTINCT code_postal, 
            code_postal, 
            code_postal, 
            COALESCE((SELECT oid FROM base.t_departements WHERE code = substr(code_postal, 1 , 3)), 0), 
            substr(code_postal, 1 , 3) || '**', 
            COALESCE((SELECT t_territoires_sante.oid FROM base.t_territoires_sante JOIN base.t_regions ON t_regions.code || '*****' = t_territoires_sante.code JOIN base.t_departements ON t_departements.region_id = t_regions.oid WHERE t_departements.code = substr(code_postal, 1 , 3)), 0)
        FROM temp.p_rss
        WHERE 
            code_postal <> '' 
            AND code_postal NOT IN (SELECT code FROM base.t_codes_postaux )
            AND substr(code_postal, 1 , 2) IN ('97', '98')
        ;
    
        INSERT INTO base.t_codes_postaux (code, texte, texte_court, departement_id, code_geographique_pmsi, territoire_sante_id)
        SELECT DISTINCT code_postal, code_postal, code_postal, 0, '*****', 0 
        FROM temp.p_rss 
        WHERE code_postal NOT IN (SELECT code FROM base.t_codes_postaux )
        ;";
    $toResult = execute_sql($sqlcmd);
    
    commit_trans();
    
    
    
    // OID code postal  
    $sqlcmd = "UPDATE temp.p_rss SET code_postal_id = t_codes_postaux.oid FROM base.t_codes_postaux 
        WHERE code_postal = t_codes_postaux.code AND (code_postal_id = 0 OR code_postal_id IS NULL OR code_postal_id <> t_codes_postaux.oid) AND code_postal <> '';";
    $toResult = execute_sql($sqlcmd);
    
    commit_trans();
    
    $sqlcmd = "UPDATE temp.p_rss SET code_postal_id = 0 WHERE code_postal = '' AND code_postal_id <> 0 OR code_postal_id IS NULL;";
    $toResult = execute_sql($sqlcmd);
    
    commit_trans();
    
    // Secteurs geographiques
    $sqlcmd = "INSERT INTO pmsi.t_secteurs_geographiques_codes_postaux (secteur_geographique_id, code_postal_id) ";
    $sqlcmd = $sqlcmd . "SELECT 0, oid FROM base.t_codes_postaux WHERE oid NOT IN (SELECT code_postal_id FROM pmsi.t_secteurs_geographiques_codes_postaux)";
    $toResult = execute_sql($sqlcmd);
    
    commit_trans();
    
    $sqlcmd = "
        INSERT INTO base.t_codes_geographiques_pmsi(code, texte, texte_court, population)
        SELECT
            code_geographique_pmsi,
            substr(base.cti_group_concat(DISTINCT trim(texte)), 1, 255),
            substr(base.cti_group_concat(DISTINCT trim(texte)), 1, 255),
            sum(population)
        FROM base.t_codes_postaux 
        WHERE 
            code_geographique_pmsi <> '' 
            AND code_geographique_pmsi <> '*****'
            AND code_geographique_pmsi NOT IN (SELECT code FROM base.t_codes_geographiques_pmsi)
        GROUP BY code_geographique_pmsi
        ORDER BY code_geographique_pmsi
        ;
        
        UPDATE base.t_codes_geographiques_pmsi 
        SET 
            texte = subview.texte,
            texte_court = subview.texte,
            population = subview.population 
        FROM
            (
            SELECT 
                code_geographique_pmsi,
                substr(base.cti_group_concat(DISTINCT trim(texte)), 1, 255) as texte,
                sum(population) as population
            FROM base.t_codes_postaux
            WHERE 
                code_geographique_pmsi <> '' 
                AND code_geographique_pmsi <> '*****'
            GROUP BY code_geographique_pmsi
            ORDER BY code_geographique_pmsi
            ) subview
        WHERE 
            t_codes_geographiques_pmsi.code = subview.code_geographique_pmsi
            AND (t_codes_geographiques_pmsi.texte <> subview.texte 
                OR t_codes_geographiques_pmsi.population <> subview.population)
        ;";
    $toResult = execute_sql($sqlcmd);
    
    commit_trans();

    $sqlcmd = "
        INSERT INTO base.t_codes_geographiques_pmsi(code, texte, texte_court, population)
        SELECT 
            code || '***', 
            'Divers ' || texte, 
            'Divers ' || texte,
            0
        FROM base.t_departements
        WHERE 
            code <> '**' 
            AND length(code) = 2
            AND code || '***' NOT IN (SELECT code FROM base.t_codes_geographiques_pmsi)
        ORDER BY code
        ;
        
        INSERT INTO base.t_codes_geographiques_pmsi(code, texte, texte_court, population)
        SELECT 
            code || '**', 
            'Divers ' || texte, 
            'Divers ' || texte, 
            0
        FROM base.t_departements 
        WHERE 
            code <> '**' 
            AND length(code) = 3
            AND code || '**' NOT IN (SELECT code FROM base.t_codes_geographiques_pmsi)
        ORDER BY code; ";
    $toResult = execute_sql($sqlcmd);
    
    commit_trans();
    
    $sqlcmd = "
        UPDATE base.t_codes_postaux 
        SET code_geographique_pmsi_id = 0 
        WHERE code_geographique_pmsi_id IS NULL
        ;
        
        UPDATE base.t_codes_postaux 
        SET code_geographique_pmsi_id = 0
        WHERE 
            code_geographique_pmsi NOT IN (SELECT code FROM base.t_codes_geographiques_pmsi)
            AND code_geographique_pmsi_id <> 0
        ;
        
        UPDATE base.t_codes_postaux 
        SET code_geographique_pmsi_id = t_codes_geographiques_pmsi.oid
        FROM base.t_codes_geographiques_pmsi
        WHERE 
            t_codes_postaux.code_geographique_pmsi = t_codes_geographiques_pmsi.code 
            AND code_geographique_pmsi_id <> t_codes_geographiques_pmsi.oid
        ;";
    
    $toResult = execute_sql($sqlcmd);
    
    commit_trans();
    
    $sqlcmd = "
        UPDATE base.t_codes_postaux 
        SET territoire_sante_id = 0 
        WHERE territoire_sante_id IS NULL
        ;
        
        UPDATE base.t_codes_postaux 
        SET territoire_sante_id = 0
        WHERE 
            territoire_sante_code NOT IN (SELECT code FROM base.t_territoires_sante)
            AND territoire_sante_id <> 0
        ;
        
        UPDATE base.t_codes_postaux 
        SET territoire_sante_id = t_territoires_sante.oid
        FROM base.t_territoires_sante
        WHERE 
            t_codes_postaux.territoire_sante_code = t_territoires_sante.code 
            AND territoire_sante_id <> t_territoires_sante.oid
        ; ";
    $toResult = execute_sql($sqlcmd);
    
    commit_trans();
    
    $sqlcmd = "
    UPDATE base.t_codes_postaux
    SET
        departement_id = t_departements.oid,
        departement_code = t_departements.code,
        departement_texte = t_departements.texte
    FROM base.t_departements
    WHERE 
        t_codes_postaux.code = t_codes_postaux.texte
        AND t_departements.code = substr(t_codes_postaux.code, 1 , 2)
        AND substr(t_codes_postaux.code, 1 , 2) NOT IN ('97', '98')
        AND (
            departement_id <> t_departements.oid OR
            departement_code <> t_departements.code OR
            departement_texte <> t_departements.texte)
    ;

    UPDATE base.t_codes_postaux
    SET
        departement_id = t_departements.oid,
        departement_code = t_departements.code,
        departement_texte = t_departements.texte
    FROM base.t_departements
    WHERE 
        t_codes_postaux.code = t_codes_postaux.texte
        AND t_departements.code = substr(t_codes_postaux.code, 1 , 3)
        AND substr(t_codes_postaux.code, 1 , 2) IN ('97', '98')
        AND (
            departement_id <> t_departements.oid OR
            departement_code <> t_departements.code OR
            departement_texte <> t_departements.texte)
    ;

    UPDATE base.t_codes_postaux
    SET
        code_geographique_pmsi = t_codes_geographiques_pmsi.code,
        code_geographique_pmsi_id = t_codes_geographiques_pmsi.oid,
        code_geographique_pmsi_code = t_codes_geographiques_pmsi.code,
        code_geographique_pmsi_texte = t_codes_geographiques_pmsi.texte
    FROM base.t_codes_geographiques_pmsi
    WHERE 
        t_codes_postaux.code = t_codes_postaux.texte
        AND t_codes_geographiques_pmsi.code = substr(t_codes_postaux.code, 1 , 2) || '***'
        AND substr(t_codes_postaux.code, 1 , 2) NOT IN ('97', '98')
        AND (
            code_geographique_pmsi <> t_codes_geographiques_pmsi.code OR
            code_geographique_pmsi_id <> t_codes_geographiques_pmsi.oid OR
            code_geographique_pmsi_code <> t_codes_geographiques_pmsi.code OR
            code_geographique_pmsi_texte <> t_codes_geographiques_pmsi.texte)
    ;

    UPDATE base.t_codes_postaux
    SET
        code_geographique_pmsi = t_codes_geographiques_pmsi.code,
        code_geographique_pmsi_id = t_codes_geographiques_pmsi.oid,
        code_geographique_pmsi_code = t_codes_geographiques_pmsi.code,
        code_geographique_pmsi_texte = t_codes_geographiques_pmsi.texte
    FROM base.t_codes_geographiques_pmsi
    WHERE 
        t_codes_postaux.code = t_codes_postaux.texte
        AND t_codes_geographiques_pmsi.code = substr(t_codes_postaux.code, 1 , 3) || '**'
        AND substr(t_codes_postaux.code, 1 , 2) IN ('97', '98')
        AND (
            code_geographique_pmsi <> t_codes_geographiques_pmsi.code OR
            code_geographique_pmsi_id <> t_codes_geographiques_pmsi.oid OR
            code_geographique_pmsi_code <> t_codes_geographiques_pmsi.code OR
            code_geographique_pmsi_texte <> t_codes_geographiques_pmsi.texte)
    ;

    UPDATE base.t_codes_postaux
    SET
        territoire_sante_id = t_territoires_sante.oid,
        territoire_sante_code = t_territoires_sante.code,
        territoire_sante_texte = t_territoires_sante.texte
    FROM 
        base.t_territoires_sante
        JOIN base.t_regions ON t_regions.code || '*****' = t_territoires_sante.code
        JOIN base.t_departements ON t_departements.region_id = t_regions.oid
    WHERE 
        t_codes_postaux.code = t_codes_postaux.texte
        AND t_departements.code = substr(t_codes_postaux.code, 1 , 2)
        AND substr(t_codes_postaux.code, 1 , 2) NOT IN ('97', '98')
        AND (   territoire_sante_id <> t_territoires_sante.oid OR
            territoire_sante_code <> t_territoires_sante.code OR
            territoire_sante_texte <> t_territoires_sante.texte)
    ;

    UPDATE base.t_codes_postaux
    SET
        territoire_sante_id = t_territoires_sante.oid,
        territoire_sante_code = t_territoires_sante.code,
        territoire_sante_texte = t_territoires_sante.texte
    FROM 
        base.t_territoires_sante
        JOIN base.t_regions ON t_regions.code || '*****' = t_territoires_sante.code
        JOIN base.t_departements ON t_departements.region_id = t_regions.oid
    WHERE 
        t_codes_postaux.code = t_codes_postaux.texte
        AND t_departements.code = substr(t_codes_postaux.code, 1 , 3)
        AND substr(t_codes_postaux.code, 1 , 2) IN ('97', '98')
        AND (   territoire_sante_id <> t_territoires_sante.oid OR
            territoire_sante_code <> t_territoires_sante.code OR
            territoire_sante_texte <> t_territoires_sante.texte)
    ; ";
    $toResult = execute_sql($sqlcmd);
    
    commit_trans();

    $sqlcmd = "
    UPDATE base.t_codes_geographiques_pmsi
    SET
        departement_id = t_departements.oid,
        departement_code = t_departements.code,
        departement_texte = t_departements.texte
    FROM base.t_departements
    WHERE 
        departement_id is null or departement_id = 0
        AND t_departements.code = substr(t_codes_geographiques_pmsi.code, 1 , 2)
        AND substr(t_codes_geographiques_pmsi.code, 1 , 2) NOT IN ('97', '98')
        AND (
            departement_id <> t_departements.oid OR
            departement_code <> t_departements.code OR
            departement_texte <> t_departements.texte)
    ;

    UPDATE base.t_codes_geographiques_pmsi
    SET
        departement_id = t_departements.oid,
        departement_code = t_departements.code,
        departement_texte = t_departements.texte
    FROM base.t_departements
    WHERE 
        departement_id is null or departement_id = 0
        AND t_departements.code = substr(t_codes_geographiques_pmsi.code, 1 , 3)
        AND substr(t_codes_geographiques_pmsi.code, 1 , 2) IN ('97', '98')
        AND (
            departement_id <> t_departements.oid OR
            departement_code <> t_departements.code OR
            departement_texte <> t_departements.texte)
    ;

    UPDATE base.t_codes_geographiques_pmsi
    SET
        territoire_sante_id = t_territoires_sante.oid,
        territoire_sante_code = t_territoires_sante.code,
        territoire_sante_texte = t_territoires_sante.texte
    FROM 
        base.t_territoires_sante
        JOIN base.t_regions ON t_regions.code || '*****' = t_territoires_sante.code
        JOIN base.t_departements ON t_departements.region_id = t_regions.oid
    WHERE 
        territoire_sante_id is null or territoire_sante_id = 0
        AND t_departements.code = substr(t_codes_geographiques_pmsi.code, 1 , 2)
        AND substr(t_codes_geographiques_pmsi.code, 1 , 2) NOT IN ('97', '98')
        AND (   territoire_sante_id <> t_territoires_sante.oid OR
            territoire_sante_code <> t_territoires_sante.code OR
            territoire_sante_texte <> t_territoires_sante.texte)
    ;

    UPDATE base.t_codes_geographiques_pmsi
    SET
        territoire_sante_id = t_territoires_sante.oid,
        territoire_sante_code = t_territoires_sante.code,
        territoire_sante_texte = t_territoires_sante.texte
    FROM 
        base.t_territoires_sante
        JOIN base.t_regions ON t_regions.code || '*****' = t_territoires_sante.code
        JOIN base.t_departements ON t_departements.region_id = t_regions.oid
    WHERE 
        territoire_sante_id is null or territoire_sante_id = 0
        AND t_departements.code = substr(t_codes_geographiques_pmsi.code, 1 , 3)
        AND substr(t_codes_geographiques_pmsi.code, 1 , 2) IN ('97', '98')
        AND (   territoire_sante_id <> t_territoires_sante.oid OR
            territoire_sante_code <> t_territoires_sante.code OR
            territoire_sante_texte <> t_territoires_sante.texte)
    ; ";
    $toResult = execute_sql($sqlcmd);
    
    commit_trans();
    
    logInfoMsg("Sejours avec anesthesie");
    
    $sqlcmd = "
        UPDATE temp.p_rss set 
            avec_anesthesie = '1'
        FROM
        (
            SELECT
                rss_id
            FROM
                temp.p_rss_actes
            WHERE
                activite_ccam = '4'
            GROUP BY rss_id
        ) subview
        WHERE 1=1
            AND subview.rss_id = p_rss.oid 
            AND avec_anesthesie IS DISTINCT FROM '1'";
    $toResult = execute_sql($sqlcmd);
    
    commit_trans();
    
    logInfoMsg("Actes avec anesthesie");
    // trouve les actes d'activité 1 qui ont un acte d'activité 4 associé
    $sqlcmd = "
        WITH w_update AS (
            SELECT
                p_rss_actes.rss_id,
                p_rss_actes.acte_id,
                p_rss_actes.date_acte,
                p_rss_actes.association_nonprevue_ccam
            FROM
                temp.p_rss_actes 
            WHERE
                p_rss_actes.activite_ccam in ('1', '4')
            GROUP BY 1 ,2, 3, 4
            HAVING count(DISTINCT p_rss_actes.activite_ccam) > 1
        )
        UPDATE temp.p_rss_actes SET
            acte_avec_anesthesie = 1
        FROM
            w_update
        WHERE 1=1
            AND p_rss_actes.activite_ccam = '1'
            AND w_update.rss_id = p_rss_actes.rss_id 
            AND w_update.acte_id = p_rss_actes.acte_id
            AND w_update.date_acte = p_rss_actes.date_acte
            AND w_update.association_nonprevue_ccam = p_rss_actes.association_nonprevue_ccam
            AND p_rss_actes.acte_avec_anesthesie IS DISTINCT FROM 1";
    $toResult = execute_sql($sqlcmd);
    
    commit_trans();

    logInfoMsg("Rajout des etablissement de provenances et destinations");
    addRssNotInTableTransfers();
    rssWithoutTransfertToNull();

    logInfoMsg("FIN TRAITEMENTS COMPLEMENTAIRES RUM. $nbE erreurs.");

    
    
}


function addRssNotInTableTransfers(){
    /**
     * Lors d'un transfert les etablissements ne sont pas tout le temps renseignes dans les lots
     * Seulement la destination grace au RSF-I
     * Si le sejour n'est pas present dans les RSF-I on recupere les etablissements depuis le prestataire
     *  */ 

    $sqlcmd = "
    WITH transfert_to_add AS(
        SELECT p_rss.oid as rss_id, 
            etablissement_provenance_id AS etablissement_provenance_id, 
			etablissement_destination_id AS  etablissement_destination_id
        FROM temp.p_rss
        LEFT JOIN temp.transferts_with_no_rss ON p_rss.no_rss = transferts_with_no_rss.no_rss
        WHERE (mode_entree IN (7, 0) OR mode_sortie IN (7, 0))
        AND NOT EXISTS (
            SELECT 1 
            FROM temp.p_rss_transferts
            WHERE p_rss.oid = p_rss_transferts.rss_id
            )
        ) INSERT INTO temp.p_rss_transferts  (rss_id, etablissement_provenance_id, etablissement_destination_id) 
        SELECT rss_id, COALESCE(etablissement_provenance_id, 0), COALESCE(etablissement_destination_id, 0)
        FROM transfert_to_add;"
        ;

    execute_sql($sqlcmd);

}


function rssWithoutTransfertToNull(){

	/**
	 * Assigne la valeure null aux séjours présents dans p_rss_transferts
	 * qui n'ont pas soit le mode d'entree soit le mode de sortie en transfert (7 ou 0)
	 */

	$sqlcmd = "
	UPDATE temp.p_rss_transferts
		SET etablissement_provenance_id = NULL
	FROM temp.p_rss  
	WHERE 
		rss_id = p_rss.oid
		AND mode_entree not in (7,0)
		AND etablissement_provenance_id IS NOT NULL;
	

	UPDATE temp.p_rss_transferts
		SET etablissement_destination_id = NULL
	FROM temp.p_rss  
	WHERE 
		rss_id = p_rss.oid
		AND mode_sortie not in (7,0)
		AND etablissement_destination_id IS NOT NULL;
	";

	execute_sql($sqlcmd);
}

function generation_rsf_post_traitements() {
    
    global $ENV_TYPEETS;
    
    global $import_id;
    global $file_VAL;
    
    global $file_exists_VAL;
    global $file_exists_VSJ;

    logInfoMsg("TRAITEMENTS COMPLEMENTAIRES RSF");
    
    begin_trans();

    
    analyse_tables();
    
    $nbE = 0;
    
    // Report du code GHS dan les prestations pour les forfaits D11, D24 et les forfaits Innovation
    // car ils ne sont pas renseign?es dns le format des RSF-B
    $sqlcmd = " UPDATE temp.p_rsf_detail SET
                    ghs_id = p_rss.ghs_id
                 FROM
                    temp.p_rss
                    JOIN pmsi.t_ghs ON t_ghs.oid = p_rss.ghs_id,
                    pmsi.t_prestations
                 WHERE 1=1
                    AND p_rsf_detail.rss_id = p_rss.oid
                    AND p_rsf_detail.est_ligne_rss = '1'
                    AND p_rsf_detail.type = 'B'
                    AND t_prestations.code = 'GHS'
                    AND t_ghs.code_text IN ('D11', 'D24', 'I01', 'I02', 'I03', 'I04', 'I05')
                    AND p_rsf_detail.ghs_id IS DISTINCT FROM p_rss.ghs_id";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_lpp );
    commit_trans();
    

    // Code PEC sur RSF TOTAL d'après VIDHOSP (ex dg)
    if ($ENV_TYPEETS != "1") {
        logInfoMsg("Prise en charge selon VIDHOSP");
        
        $sqlcmd = "UPDATE temp.p_rsf_total SET 
                        code_pec = CASE WHEN p_vidhosp.code_pec <> '0' AND pole_oap_code = 'AL' THEN '1' ELSE p_vidhosp.code_pec END,
                        code_pec_id = CASE WHEN p_vidhosp.code_pec <> '0' AND pole_oap_code = 'AL' THEN (SELECT oid FROM base.t_pec WHERE code = '1') ELSE p_vidhosp.code_pec_id END,
                        regime = p_vidhosp.regime,
                        regime_id = p_vidhosp.regime_id,
                        nature_pec = p_vidhosp.nature_pec, 
                        nature_pec_id = p_vidhosp.nature_pec_id, 
                        taux_remboursement = p_vidhosp.taux_remboursement,
                        justificatif_exo = p_vidhosp.justificatif_exo,
                        exoneration_tm_id = p_vidhosp.exoneration_tm_id,
                        matricule_assure = p_vidhosp.matricule_assure,
                        cle_matricule_assure = p_vidhosp.cle_matricule_assure,
                        type_contrat_oc_id = p_vidhosp.type_contrat_oc_id,
                        motif_non_facturation_id = p_vidhosp.motif_non_facturation_id,
                        code_pec_fj_id = p_vidhosp.code_pec_fj_id,
                        facturation_18euros = p_vidhosp.facturation_18euros,
                        facturation_18euros_id = p_vidhosp.facturation_18euros_id,
                        no_ipp = p_vidhosp.no_ipp
                    FROM 
                        temp.p_rss
                        JOIN temp.p_vidhosp ON p_rss.oid = p_vidhosp.rss_id
                        JOIN pmsi.t_ghm_c ON ghm_id = t_ghm_c.oid
                    WHERE 
                        p_rsf_total.rss_id = p_rss.oid
                        AND p_rss.import_id = $import_id
                        AND (
                            p_rsf_total.code_pec IS DISTINCT FROM CASE WHEN p_vidhosp.code_pec <> '0' AND pole_oap_code = 'AL' THEN '1' ELSE p_vidhosp.code_pec END
                            OR p_rsf_total.code_pec_id IS DISTINCT FROM CASE WHEN p_vidhosp.code_pec <> '0' AND pole_oap_code = 'AL' THEN (SELECT oid FROM base.t_pec WHERE code = '1') ELSE p_vidhosp.code_pec_id END
                            OR p_rsf_total.regime IS DISTINCT FROM p_vidhosp.regime
                            OR p_rsf_total.regime_id IS DISTINCT FROM p_vidhosp.regime_id
                            OR p_rsf_total.nature_pec IS DISTINCT FROM p_vidhosp.nature_pec
                            OR p_rsf_total.nature_pec_id IS DISTINCT FROM p_vidhosp.nature_pec_id
                            OR p_rsf_total.taux_remboursement IS DISTINCT FROM p_vidhosp.taux_remboursement
                            OR p_rsf_total.matricule_assure IS DISTINCT FROM p_vidhosp.matricule_assure
                            OR p_rsf_total.cle_matricule_assure IS DISTINCT FROM p_vidhosp.cle_matricule_assure
                            OR p_rsf_total.justificatif_exo IS DISTINCT FROM p_vidhosp.justificatif_exo
                            OR p_rsf_total.exoneration_tm_id IS DISTINCT FROM p_vidhosp.exoneration_tm_id
                            OR p_rsf_total.type_contrat_oc_id IS DISTINCT FROM p_vidhosp.type_contrat_oc_id
                            OR p_rsf_total.motif_non_facturation_id IS DISTINCT FROM p_vidhosp.motif_non_facturation_id
                            OR p_rsf_total.code_pec_fj_id IS DISTINCT FROM p_vidhosp.code_pec_fj_id
                            OR p_rsf_total.facturation_18euros IS DISTINCT FROM p_vidhosp.facturation_18euros
                            OR p_rsf_total.facturation_18euros_id IS DISTINCT FROM p_vidhosp.facturation_18euros_id
                            OR p_rsf_total.no_ipp IS DISTINCT FROM p_vidhosp.no_ipp
                        ); ";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW_lpp );
        commit_trans();

    //Information CMU - Espic
            $sqlcmd = "UPDATE pmsi.p_rsf_total SET 
                        pat_benef_cmu = cmu::integer
                    FROM (
                        SELECT 
                        cmu,
                        no_rss
                        FROM pmsi.p_vidhosp
                        JOIN pmsi.p_rss on p_rss.oid = p_vidhosp.rss_id
                        WHERE cmu BETWEEN '1' AND '9'
                        ) subq1
                    WHERE 1=1
                        AND subq1.no_rss = p_rsf_total.no_rss
                        AND (pat_benef_cmu IS NULL OR pat_benef_cmu::text = '')
                        ; ";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW_lpp );
        commit_trans();
        
        // Depuis M01 2019, le numero IPP est renseignable dans VIDHOSP. S'il l'est (différent de 0, valeur par défaut), on le met à jour dans les RSS
        logInfoMsg("IPP selon VIDHOSP");
        
        $sqlcmd = "UPDATE temp.p_rss SET 
                        no_patient = p_vidhosp.no_ipp
                    FROM 
                        temp.p_vidhosp
                    WHERE 1=1
                        AND p_rss.oid = p_vidhosp.rss_id
                        AND p_vidhosp.no_ipp != 0
                        AND p_vidhosp.no_ipp != p_rss.no_patient
                    ; ";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW_lpp );
        commit_trans();
        
    }
    
    
    if ($ENV_TYPEETS == "1") {

        logInfoMsg("GHS des non facturés");
        
        $sqlcmd = "UPDATE temp.p_rss SET ghs_id = (SELECT oid from pmsi.t_ghs WHERE code = 9999)
            WHERE ghs_id = 0 AND ghm_id IN (SELECT oid FROM pmsi.t_ghm WHERE code IN ('09Z02Z', '09Z02A', '14Z04Z', '14Z08Z', '15Z10E', '23Z03Z', '24Z15Z', '24Z19Z', '28Z05Z', '28Z06Z'));";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
        commit_trans();

        $sqlcmd = "UPDATE temp.p_rss SET ghs_id = ghs_1_id
            FROM pmsi.t_ghm 
            WHERE p_rss.ghm_id <> 0 AND p_rss.ghm_id = t_ghm.oid
            AND p_rss.ghs_id = 0
            AND ghs_1_id <> 0
            AND ghs_2_id = 0 ";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
        commit_trans();
        
        $sqlcmd = "UPDATE temp.p_rss SET ghs_id = 
            CASE 
                WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z02Z' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5800)
                WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z03Z' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5801)
                WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z04E' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5802)
                WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z05A' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5803)
                WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z05B' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5804)
                WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z05C' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5805)
                WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z05D' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5806)
                WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z06A' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5807)
                WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z06B' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5808)
                WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z06C' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5809)
                WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z06D' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5810)
                WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z07A' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5811)
                WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z07B' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5812)
                WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z07C' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5813)
                WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z07D' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5814)
                WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z08E' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5815)
                WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z09E' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5817)

                WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z02Z' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5819)
                WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z03Z' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5820)
                WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z04E' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5821)
                WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z05A' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5822)
                WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z05B' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5823)
                WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z05C' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5824)
                WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z05D' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5825)
                WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z06A' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5826)
                WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z06B' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5827)
                WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z06C' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5828)
                WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z06D' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5829)
                WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z07A' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5830)
                WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z07B' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5831)
                WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z07C' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5832)
                WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z07D' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5833)
                WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z08E' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5834)
                WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z09E' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5836)

            ELSE 0 END

            FROM pmsi.t_ghm
            WHERE ghs_id = 0 AND p_rss.ghm_id = t_ghm.oid
            and p_rss.ghm_id > 0";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
        commit_trans();
    
    }
    
    
    
    logInfoMsg("Initialisation Acte principal RSS");
    
    $sqlcmd = "UPDATE temp.p_rss SET acte_principal_id = COALESCE(subview.acte_principal_1_id, acte_principal_4_id, 0) FROM 
            (SELECT rss_id,  
                (MAX(ARRAY[CASE WHEN activite_ccam = '1' THEN CASE WHEN type_etablissement IN ('2','3') THEN t_actes_c.icr_public_atih_1 ELSE t_actes_c.icr_prive_atih_1 END ELSE 0 END, acte_id]))[2] as acte_principal_1_id ,
                (MAX(ARRAY[CASE WHEN activite_ccam = '4' THEN CASE WHEN type_etablissement IN ('2','3') THEN t_actes_c.icr_public_atih_4 ELSE t_actes_c.icr_prive_atih_4 END ELSE 0 END, acte_id]))[2] as acte_principal_4_id 
            FROM temp.p_rss_actes
            JOIN pmsi.t_actes_c ON p_rss_actes.acte_id = t_actes_c.oid
            LEFT JOIN base.t_finess ON p_rss_actes.finess = t_finess.code
            WHERE activite_ccam <> '5' GROUP BY rss_id) subview 
            WHERE p_rss.oid = subview.rss_id AND (p_rss.acte_principal_id = 0 or p_rss.acte_principal_id IS NULL)";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();
    
    $sqlcmd = "UPDATE temp.p_rss SET acte_principal_id = 0 WHERE acte_principal_id IS NULL ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();
    
    logInfoMsg("Initialisation Prestation principale RSS");
    
    
    $sqlcmd = "DROP TABLE IF EXISTS w_prestation_principale;
    CREATE TEMP TABLE w_prestation_principale AS
    SELECT
        rss_id,
        (MAX(
            ARRAY[
                CASE 
                    WHEN p_rsf_detail.type = 'B' AND t_prestations.code = 'GHS' THEN 9999999999999
                    WHEN p_rsf_detail.type = 'B' AND t_prestations.code = 'EXH' THEN 9999999999998
                    WHEN t_prestations.code IN ('SE1', 'SE2', 'SE3', 'SE4', 'SE5', 'SE6', 'SE7', 'ATU', 'FFM', 'APE', 'FFM' , 'AP2', 'FPI') THEN 9999999999997
                    WHEN p_rsf_detail.type = 'B' AND t_prestations.code = 'MAR' THEN 9999999999996
                    WHEN p_rsf_detail.type = 'B' AND t_prestations.code = 'PJ' THEN 9999999999995
                    ELSE base_remboursement
                END,
                prestation_id
                ]
        ))[2] AS prestation_principale_id
    FROM temp.p_rsf_detail
    JOIN pmsi.t_prestations ON prestation_id = t_prestations.oid
    WHERE p_rsf_detail.est_ligne_rss = '1'
    GROUP BY 1;";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();


    $sqlcmd = "UPDATE temp.p_rss
    SET prestation_principale_id = w_prestation_principale.prestation_principale_id
    FROM w_prestation_principale
    WHERE p_rss.oid = w_prestation_principale.rss_id AND (p_rss.prestation_principale_id = 0 OR p_rss.prestation_principale_id IS NULL);";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();
    

    $sqlcmd = "UPDATE temp.p_rss 
    SET prestation_principale_id = t_prestations.oid 
    FROM pmsi.t_prestations  
    WHERE ghm_id > 0 AND
        (p_rss.prestation_principale_id = 0 OR p_rss.prestation_principale_id IS NULL) AND
        t_prestations.code = 'GHS' AND 
        p_rss.oid NOT IN (SELECT rss_id FROM temp.p_rsf_detail WHERE p_rsf_detail.est_ligne_rss = '1'); ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();


    $sqlcmd = "UPDATE temp.p_rss SET prestation_principale_id = 0 WHERE prestation_principale_id IS NULL;";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();

    // Mettre à jour les indication_id dans la table p_rss_ucd
	logInfoMsg("Traitement indication UCD");
	$sqlcmd = "
		UPDATE temp.p_rss_ucd SET
			indication_id = t_indication.oid
		FROM
			pmsi.t_indication
		WHERE 1=1
			AND p_rss_ucd.indication = t_indication.code
		";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	commit_trans();

    
    $sqlcmd = "INSERT INTO temp.p_rsf_detail(finess, no_rss, date_debut, date_fin, nombre, ghs_id, prestation_id, rss_id, type, coefficient_mco, coefficient_geo, est_ligne_rss, est_ligne_rum, no_rum, unite_medicale_id, base_remboursement_rum)  ";
    $sqlcmd = $sqlcmd . "SELECT p_rss.finess, p_rss.no_rss, p_rss.date_entree, p_rss.date_sortie, 1, 0, (SELECT oid FROM pmsi.t_prestations WHERE code = 'GHS'), p_rss.oid, 'B', ";
    $sqlcmd = $sqlcmd . "(SELECT coefficient_mco FROM temp.p_rsf_detail WHERE prestation_id In (SELECT oid FROM pmsi.t_prestations WHERE code = 'GHS') AND coefficient_mco > 0 ORDER BY date_fin DESC limit 1), 1,  '1', '0', 0, 0, 0  ";
    $sqlcmd = $sqlcmd . "FROM temp.p_rss, temp.p_rsf_total ";
    $sqlcmd = $sqlcmd . "WHERE ghm_id IN (SELECT oid FROM pmsi.t_ghm WHERE code LIKE '15%') AND ";
    $sqlcmd = $sqlcmd . "p_rsf_total.rss_id = p_rss.oid AND p_rsf_total.nb_ghs = 0 AND ";
    $sqlcmd = $sqlcmd . "oid NOT IN (SELECT rss_id FROM temp.p_rsf_detail WHERE prestation_id In (SELECT oid FROM pmsi.t_prestations WHERE code = 'GHS')) ";
    $toResult = execute_sql($sqlcmd);
    commit_trans();
    
    $sqlcmd = "INSERT INTO temp.p_rsf_detail(finess, no_rss, date_debut, date_fin, nombre, ghs_id, prestation_id, rss_id, type, coefficient_mco, coefficient_geo, est_ligne_rss, est_ligne_rum, no_rum, unite_medicale_id, base_remboursement_rum)  ";
    $sqlcmd = $sqlcmd . "SELECT p_rss.finess, p_rss.no_rss, p_rss.date_entree, p_rss.date_sortie, 1, 0, (SELECT oid FROM pmsi.t_prestations WHERE code = 'GHS'), p_rss.oid, 'B', ";
    $sqlcmd = $sqlcmd . "0, 1,  '1', '0', 0, 0, 0  ";
    $sqlcmd = $sqlcmd . "FROM temp.p_rss, temp.p_rsf_total ";
    $sqlcmd = $sqlcmd . "WHERE ghm_id IN (SELECT oid FROM pmsi.t_ghm WHERE code IN ('24Z10E', '24Z12Z', '24Z21Z', '24Z23Z', '24Z24Z')) AND ";
    $sqlcmd = $sqlcmd . "p_rsf_total.rss_id = p_rss.oid AND p_rsf_total.nb_ghs = 0 AND ";
    $sqlcmd = $sqlcmd . "oid NOT IN (SELECT rss_id FROM temp.p_rsf_detail WHERE prestation_id In (SELECT oid FROM pmsi.t_prestations WHERE code = 'GHS')) ";
    $toResult = execute_sql($sqlcmd);
    commit_trans();
    
    // Mise à jour coefficient calculé
    // Modif CLA le 06-09-2016 On joine sur p_rss (rss_id ET ghs_id) pour ne garder que les GHS principaux et ne pas traiter les GHS des bébés ou des suppléments dialyse
    $sqlcmd = "UPDATE temp.p_rsf_detail SET 
                coefficient = round(p_rsf_detail.base_remboursement / p_rsf_detail.prix_unitaire / p_rsf_detail.coefficient_mco / p_rsf_detail.nombre, 5)::numeric(18 , 5),
                update_rules = array_append(update_rules, 41)
            FROM 
                temp.p_rss, 
                pmsi.t_prestations
            WHERE 1=1
                AND p_rss.oid = p_rsf_detail.rss_id AND p_rss.ghs_id = p_rsf_detail.ghs_id
                AND p_rsf_detail.type = 'B' 
                AND p_rsf_detail.est_ligne_rss = '1' 
                AND p_rsf_detail.prestation_id = t_prestations.oid  
                AND p_rsf_detail.prix_unitaire > 0 
                AND p_rsf_detail.nombre > 0
                AND p_rsf_detail.coefficient_mco > 0
                AND p_rsf_detail.base_remboursement > 0 
                AND p_rss.import_id = $import_id 
                AND p_rss.date_sortie >= '20090301'::date
                AND t_prestations.code = 'GHS'
				AND valorise_valosejace <> '1'
                AND round(p_rsf_detail.base_remboursement / p_rsf_detail.prix_unitaire / p_rsf_detail.coefficient_mco / p_rsf_detail.nombre, 3) <  1 
                AND p_rsf_detail.coefficient <> round(p_rsf_detail.base_remboursement / p_rsf_detail.prix_unitaire / p_rsf_detail.coefficient_mco / p_rsf_detail.nombre, 5)::numeric(18 , 5);
            ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    

    // Mise à jour coefficient si 0
    $sqlcmd = "UPDATE temp.p_rsf_detail 
            SET coefficient = 1,
                update_rules = array_append(update_rules, 42)
            WHERE coefficient = 0 OR coefficient IS NULL";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    logInfoMsg("Assurance");
    
    // Création d'une table de travail où on recense les séjours avec ME = 0, MS = 0 et DA = Z7580
    // Normalement, les séjours ME = 0 et MS = 0 sont exclus et marqués comme 'Prestation inter établissement' sauf qu'il apparait à la lecture
    // des tableaux Mat2a que les séjours avec ME = 0, MS = 0 et DA = Z7580 ne sont visiblement pas exclus
    // Modif CLA 18-07-2016, la condition sur le code CMD 28 semble poser problème dans certains rares cas, je l'enlève
    $sqlcmd = "DROP TABLE IF EXISTS w_z7580; CREATE TEMP TABLE w_z7580 AS
                SELECT 
                    p_rss.oid as rss_id,
                    1 as keep_sejour
                FROM temp.p_rss
                    JOIN pmsi.t_ghm_c ON p_rss.ghm_id = t_ghm_c.oid
                    LEFT JOIN temp.p_rss_diagnostics ON p_rss.oid = p_rss_diagnostics.rss_id
                    LEFT JOIN pmsi.t_diagnostics on t_diagnostics.oid = p_rss_diagnostics.diagnostic_id
                WHERE
                    p_rss.import_id = $import_id
                    AND (t_diagnostics.code = 'Z7580' OR t_ghm_c.section_code[8] IN ('S01', 'S02', 'S03', 'S04'))
                    AND mode_sortie = '0'
                    AND mode_entree = '0'
                GROUP BY 1;";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();
    
    // CLA le 11-04-2018 Il semblerait que les séjours qui sont dans le fichier .ano (et donc dans le RSA) mais pas dans le vidhosp
    // soient quand même valorisés, d'où l'ajout d'une condiciton sur le numéro anonyme like '%XXXXXXXXX%'
    // Traitement epmsi = 26 : non valorisé par VALOSEJ
    $sqlcmd = "
            WITH w_vidhosp AS (
                SELECT rss_id FROM temp.p_vidhosp
                WHERE no_anonyme like '%XXXXXXXXXXXXX%'
            )
            UPDATE temp.p_rss 
                SET traitement_epmsi = 
                    CASE 
                    WHEN p_rss.en_cours LIKE '1' THEN '00'
                    WHEN p_rss.ghm_id IN (SELECT oid FROM pmsi.t_ghm WHERE code LIKE '90%' AND CODE <> '90H02Z' AND CODE <> '90H03Z')  THEN '11'
                    WHEN p_rss.mode_entree = '0' AND p_rss.mode_sortie = '0' AND w_z7580.keep_sejour IS DISTINCT FROM 1 AND (p_rss.valorise_valosejace IS DISTINCT FROM '1' OR p_rss.traitement_epmsi < '30') THEN '12'
                    WHEN p_rss.ghs_id IN (SELECT oid FROM pmsi.t_ghs WHERE code = 9999) THEN '13'

                    WHEN t_finess.type_etablissement IN ('2', '3') AND subview.nb_vidhosp > 0 AND p_rss.ghm_id > 0 AND p_rss.oid NOT IN (SELECT rss_id FROM temp.p_vidhosp) THEN '21' 
                    WHEN t_finess.type_etablissement IN ('2', '3') AND p_ctl_mt2a.erreur_genrsa = '1' THEN '21' 
                    WHEN t_finess.type_etablissement IN ('2', '3') AND p_ctl_mt2a.erreur_genrsa = '2' THEN '22' 
                    WHEN t_finess.type_etablissement IN ('2', '3') AND trim(t_pec.code) IN ('3') THEN '23' 
                    WHEN t_finess.type_etablissement NOT IN ('2', '3') AND trim(t_pec.code) IN ('2', '3', '4') THEN '24'
                    WHEN t_finess.type_etablissement IN ('2', '3') AND p_ctl_mt2a.erreur_genrsa = '3' THEN '24'                     
                    WHEN t_finess.type_etablissement IN ('2', '3') AND trim(t_pec.code) IN ('0', 'X') AND w_vidhosp.rss_id IS NULL THEN '24'
                    WHEN p_rss.traitement_epmsi = '26' THEN '26'
                    ELSE '30' END
                FROM temp.p_rsf_total, base.t_finess, base.t_pec, temp.p_rss p_rss_bis
                    LEFT JOIN
                                (SELECT w_rss.mois_sortie, count(*) AS nb_vidhosp 
                                FROM temp.p_rss w_rss, temp.p_vidhosp w_vidhosp
                                WHERE w_rss.oid = w_vidhosp.rss_id
                                GROUP BY w_rss.mois_sortie) subview
                                ON p_rss_bis.mois_sortie = subview.mois_sortie
                    LEFT JOIN temp.p_ctl_mt2a ON (p_rss_bis.oid = p_ctl_mt2a.rss_id)
                    LEFT JOIN w_z7580 ON w_z7580.rss_id = p_rss_bis.oid
                    LEFT JOIN w_vidhosp ON w_vidhosp.rss_id = p_rss_bis.oid
                WHERE p_rss_bis.oid = p_rss.oid 
                AND t_pec.oid = p_rsf_total.code_pec_id
                AND p_rss.import_id = $import_id
                AND p_rsf_total.rss_id = p_rss.oid 
                AND t_finess.code = p_rss.finess
                AND (p_rss.traitement_epmsi <>  
                    CASE 
                    WHEN p_rss.en_cours LIKE '1' THEN '00'
                    WHEN p_rss.ghm_id IN (SELECT oid FROM pmsi.t_ghm WHERE code LIKE '90%' AND CODE <> '90H02Z' AND CODE <> '90H03Z')  THEN '11'
                    WHEN p_rss.mode_entree = '0' AND p_rss.mode_sortie = '0'  THEN '12'
                    WHEN p_rss.ghs_id IN (SELECT oid FROM pmsi.t_ghs WHERE code = 9999) THEN '13'

                    WHEN t_finess.type_etablissement IN ('2', '3') AND subview.nb_vidhosp > 0 AND p_rss.ghm_id > 0 AND p_rss.oid NOT IN (SELECT rss_id FROM temp.p_vidhosp) THEN '21' 
                    WHEN t_finess.type_etablissement IN ('2', '3') AND p_ctl_mt2a.erreur_genrsa = '1' THEN '21' 
                    WHEN t_finess.type_etablissement IN ('2', '3') AND p_ctl_mt2a.erreur_genrsa = '2' THEN '22' 
                    WHEN t_finess.type_etablissement IN ('2', '3') AND trim(t_pec.code) IN ('3') THEN '23' 
                    WHEN t_finess.type_etablissement NOT IN ('2', '3') AND trim(t_pec.code) IN ('2', '3', '4') THEN '24'
                    WHEN t_finess.type_etablissement IN ('2', '3') AND p_ctl_mt2a.erreur_genrsa = '3' THEN '24'                     
                    WHEN t_finess.type_etablissement IN ('2', '3') AND trim(t_pec.code) IN ('0', 'X') THEN '24' 
                    ELSE '30' END OR p_rss.traitement_epmsi IS NULL)";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();

    // IC-3071 traité le 22-11-2016
    // Pour les exOQN, si pas de GHS dans le RSS, MàJ du GHS d'après la table des RSA
    logInfoMsg("MaJ du GHS d'apres le RSA pour les RSS sans GHS");
    if ($ENV_TYPEETS == "1") {
        // 15 - RSF-B Supprimés _ Séjour avec plusieurs GHS hors cas admis 
        // (voir règle d'exclusion dans la description du tableau 1.V.1.fsuphc dans le guide de lecture OVALIDE OQN)
        // Condition and sum(nombre) <> 1 rajouté par CLA le 22-09-2015 pour ne pas impacter les RSF qui ont des écritures d'annulation (nature_operation = 5) et où au final, il ne reste qu'un GHS
        // GHS 9614 (séances hyperbare) et 9615 (aphérèses) rajoutés le 06-09-2016 par CLA
        
        $sqlcmd = "
            UPDATE temp.p_rss 
            SET traitement_epmsi = '30'
            FROM (  SELECT
                        rss_id
                    FROM
                        temp.p_rsf_detail
                        JOIN temp.p_rss ON p_rss.oid = p_rsf_detail.rss_id
                        JOIN pmsi.t_prestations ON t_prestations.oid = p_rsf_detail.prestation_id
                        JOIN pmsi.t_ghs ON t_ghs.oid = p_rsf_detail.ghs_id
                        JOIN pmsi.t_ghm ON t_ghm.oid = p_rss.ghm_id
                        JOIN pmsi.t_cmd ON t_cmd.oid = t_ghm.cmd_id
                    WHERE 
                        t_prestations.code = 'GHS' AND
                        t_ghs.code NOT IN (9605, 9604, 9614, 9615) AND
                        p_rsf_detail.type = 'B' AND
                        p_rsf_detail.est_ligne_rss = '1' AND
                        t_cmd.code NOT IN ('14', '28')
                    GROUP BY 1
                    HAVING count(p_rsf_detail.ghs_id) > 1 AND sum(nombre) <> 1
                    ) subview
            WHERE subview.rss_id = p_rss.oid
        ";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
        commit_trans();

        $sqlcmd = "
            UPDATE temp.p_rss SET
                ghs_id = ghs_rsa.oid
            FROM
                temp.p_rsa
                JOIN pmsi.t_ghs ghs_rsa ON p_rsa.ghs_genrsa_id = ghs_rsa.oid,
                pmsi.t_ghs ghs_rss
            WHERE 1=1
                AND p_rss.ghs_id = ghs_rss.oid
                AND p_rsa.rss_id = p_rss.oid
                AND ghs_rss.code IN (0, 9999)
                AND p_rss.ghs_id IS DISTINCT FROM ghs_rsa.oid";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );
        $nb_updates = (is_resource($toResult) == true) ? pg_affected_rows($toResult) : 0;        
        echo ". " . $nb_updates . " GHS modifiés";
    } else {
        $sqlcmd = "
            UPDATE temp.p_rss 
            SET traitement_epmsi = '15'
            FROM (  SELECT
                        rss_id
                    FROM
                        temp.p_rsf_detail
                        JOIN temp.p_rss ON p_rss.oid = p_rsf_detail.rss_id
                        JOIN pmsi.t_prestations ON t_prestations.oid = p_rsf_detail.prestation_id
                        JOIN pmsi.t_ghs ON t_ghs.oid = p_rsf_detail.ghs_id
                        JOIN pmsi.t_ghm ON t_ghm.oid = p_rss.ghm_id
                        JOIN pmsi.t_cmd ON t_cmd.oid = t_ghm.cmd_id
                    WHERE 
                        t_prestations.code = 'GHS' AND
                        t_ghs.code NOT IN (9605, 9604, 9614, 9615) AND
                        p_rsf_detail.type = 'B' AND
                        p_rsf_detail.est_ligne_rss = '1' AND
                        t_cmd.code NOT IN ('14', '28')
                    GROUP BY 1
                    HAVING count(p_rsf_detail.ghs_id) > 1 AND sum(nombre) <> 1
                    ) subview
            WHERE subview.rss_id = p_rss.oid
        ";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
        commit_trans();
    }
    
    
    // 15 - RSF-B Supprimés _ RSFB/C avec PU différent du tarif BO
    
    /* SAUF SI FICHIER VAL EN LIGNE
     * (voir règle d'exclusion dans la description du tableau 1.V.1.fsupex dans le guide de lecture OVALIDE OQN)
     * Si le prix unitaire de la ligne RSFB est différent de celui de la prestation * multiplié par le coefficient mco de la table base.t_finess sur la période du dossier, 
     * Et si le prix unitaire de la ligne RSFB est différent de celui de la prestation sans coefficient MCO
     * on supprime les dossier.
     * ATTENTION, sur le privé, le rss est pointé,
     *              sur le public, les montants de la ligne RSF B sont remis à zéro car le reste du séjour peut être valorisé
     * CLA 2019-03-08 Les externes avec CMU sont autorisés (empirique) à avoir un prix unitaire différent du prix unitaire du BO. Cela étant,
     * leur valorisation se fait avec le prix unitaire du BO. Va comprendre Charles...
     */
    if (! $file_exists_VAL) {
        logInfoMsg("Pb pu");
        $sqlcmd = "
            DROP TABLE IF EXISTS w_forfaits;
            
            CREATE TEMP TABLE w_forfaits AS
            SELECT 
                t_finess.type_etablissement,
                p_rss.oid as rss_id,p_rss.no_rss,
                p_rsf_detail.CTID AS rsf_CTID,
                p_rss.date_sortie,
                t_prestations.code,
                p_rsf_detail.prix_unitaire, 
                COALESCE(p_rsf_total.pat_benef_cmu, '0') AS cmu,
                round(CASE 
                    WHEN p_rss.date_sortie < t_finess.date_debut_coefficient_mco_2 THEN coefficient_mco_1 * t_prestation_tarif.tarif
                    WHEN p_rss.date_sortie BETWEEN t_finess.date_debut_coefficient_mco_2 AND t_finess.date_debut_coefficient_mco_3 THEN coefficient_mco_2 * t_prestation_tarif.tarif
                    WHEN p_rss.date_sortie BETWEEN t_finess.date_debut_coefficient_mco_3 AND t_finess.date_debut_coefficient_mco_4 THEN coefficient_mco_3 * t_prestation_tarif.tarif
                    WHEN p_rss.date_sortie BETWEEN t_finess.date_debut_coefficient_mco_4 AND t_finess.date_debut_coefficient_mco_5 THEN coefficient_mco_4 * t_prestation_tarif.tarif
                    WHEN p_rss.date_sortie BETWEEN t_finess.date_debut_coefficient_mco_5 AND t_finess.date_debut_coefficient_mco_6 THEN coefficient_mco_5 * t_prestation_tarif.tarif
                    WHEN p_rss.date_sortie BETWEEN t_finess.date_debut_coefficient_mco_6 AND t_finess.date_debut_coefficient_mco_7 THEN coefficient_mco_6 * t_prestation_tarif.tarif
                    WHEN p_rss.date_sortie BETWEEN t_finess.date_debut_coefficient_mco_7 AND t_finess.date_debut_coefficient_mco_8 THEN coefficient_mco_7 * t_prestation_tarif.tarif
                    WHEN p_rss.date_sortie BETWEEN t_finess.date_debut_coefficient_mco_8 AND t_finess.date_debut_coefficient_mco_9 THEN coefficient_mco_8 * t_prestation_tarif.tarif
                    WHEN p_rss.date_sortie >= t_finess.date_debut_coefficient_mco_9 THEN coefficient_mco_9 * t_prestation_tarif.tarif
                    ELSE t_prestation_tarif.tarif
                END, 2) AS prix_tarif_avec_coeff, 
                t_prestation_tarif.tarif AS prix_tarif_sauf_coeff
            FROM 
                temp.p_rsf_detail
            JOIN 
                temp.p_rss ON p_rss.oid = p_rsf_detail.rss_id
                JOIN temp.p_rsf_total ON p_rsf_total.rss_id = p_rsf_detail.rss_id
                JOIN base.t_finess ON t_finess.code = p_rss.finess
                JOIN pmsi.t_prestations ON t_prestations.oid = p_rsf_detail.prestation_id
                JOIN pmsi.t_prestation_tarif ON t_prestation_tarif.prestation_id = t_prestations.oid 
                    AND (t_finess.type_etablissement = t_prestation_tarif.type_ets OR
                        t_finess.type_etablissement <> 1 AND t_prestation_tarif.type_ets = '2')
                    AND p_rss.date_sortie BETWEEN t_prestation_tarif.date_debut AND t_prestation_tarif.date_fin
            WHERE
                t_prestations.code IN ('FFM', 'ATU', 'SE1', 'SE2', 'SE3', 'SE4', 'SE5', 'SE6', 'SE7', 'FSD', 'VDE', 'APE', 'AP2', 'FPI')
                AND p_rss.import_id = $import_id;
            
            
            UPDATE temp.p_rss 
            SET traitement_epmsi = '15'
            FROM 
                (SELECT rss_id 
                FROM w_forfaits 
                WHERE 
                    type_etablissement NOT IN ('2','3') AND
                    abs(prix_unitaire - prix_tarif_avec_coeff) > 0.01 AND
                    abs(prix_unitaire - prix_tarif_sauf_coeff) > 0.01
                ) subview
            WHERE subview.rss_id = p_rss.oid;

            UPDATE temp.p_rsf_detail
            SET prix_unitaire = CASE WHEN w_forfaits.cmu = '1' THEN p_rsf_detail.prix_unitaire ELSE prix_tarif_sauf_coeff END,
                base_remboursement = p_rsf_detail.base_remboursement,
                base_remboursement_sauf_transition = p_rsf_detail.base_remboursement_sauf_transition,
                nombre = p_rsf_detail.nombre,
                sejour_remboursable = p_rsf_detail.sejour_remboursable,
                update_rules = array_append(update_rules, 43)
            FROM w_forfaits 
            WHERE w_forfaits.rsf_CTID = p_rsf_detail.CTID AND
                type_etablissement IN ('2','3') AND
                abs(p_rsf_detail.prix_unitaire - prix_tarif_avec_coeff) > 0.01 AND
                abs(p_rsf_detail.prix_unitaire - prix_tarif_sauf_coeff) > 0.01;";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
        commit_trans();
    }
    
    // SI FICHIER VAL EN LIGNE
    if ($file_exists_VAL) {
    
            $file_VAL_pg = realpath($file_VAL);
            $file_VAL_pg = str_replace('\\','//',$file_VAL_pg);
            
            $yep = '"';
            
            $sqlcmd = "
            DROP TABLE IF EXISTS w_VAL_ERR;
            DROP SEQUENCE IF EXISTS w_VAL_ERR_seq;
            CREATE TEMP SEQUENCE w_VAL_ERR_seq;

            CREATE TEMP TABLE w_VAL_ERR (
                    data text, 
                    line_type text DEFAULT '', 
                    sequence bigint DEFAULT nextval('w_VAL_ERR_seq'::regclass),
                    no_rss numeric
                    );
            TRUNCATE w_VAL_ERR;

            COPY w_VAL_ERR (data) FROM '$file_VAL_pg' WITH DELIMITER AS E'\01' ;
            
            UPDATE w_VAL_ERR
            SET line_type = 
                CASE 
                    WHEN sequence BETWEEN sequence_rss + 1 AND sequence_ext - 1 THEN 'RSS'
                    WHEN sequence > sequence_ext THEN 'EXT'
                    ELSE '' END,
                no_rss = base.cti_to_number(replace(split_part(data,';',2),'$yep',''))
                
            FROM
                (SELECT COALESCE(MIN(sequence),0) AS sequence_rss FROM w_VAL_ERR WHERE data LIKE 'NUMTEST;NUMRSS%') subview_rss,
                (SELECT COALESCE(MIN(sequence),999999999) AS sequence_ext FROM w_VAL_ERR WHERE data LIKE 'NUMTEST;NUMFACT%') subview_ext
            WHERE split_part(data,';',4) <> '';


            CREATE INDEX w_val_err_i1
              ON w_val_err
              USING btree
              (no_rss);

            /*
                Modif par CLA le 07-06-2017
                Désactivation de la ligne qui ignore les séjours de séances qui
                présentent une erreur de type 13
                JIRA IC-3973
            */
            UPDATE temp.p_rss
            SET traitement_epmsi = '15'
            FROM w_val_err
            WHERE import_id = $import_id AND 
                p_rss.no_rss = w_val_err.no_rss AND
                line_type = 'RSS' AND w_val_err.no_rss <> 0 AND
                traitement_epmsi = '30'
                --AND ((split_part(data,';',1) = '13' AND substr(split_part(data,';',4), 1, 2) <> '28') OR split_part(data,';',1) <> '13')
                ;


            UPDATE temp.p_rss
            SET traitement_epmsi = '15'
            FROM w_val_err
            JOIN temp.p_rsf_total ON p_rsf_total.no_facture = w_val_err.no_rss
            WHERE import_id = $import_id AND 
                p_rsf_total.no_rss = p_rss.no_rss AND
                line_type = 'EXT' AND w_val_err.no_rss <> 0 AND
                traitement_epmsi = '30';
            
            ";
            $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
            commit_trans();
    
    }
    
    $sqlcmd = "UPDATE temp.p_rss SET traitement_epmsi = '0' WHERE traitement_epmsi IS NULL;";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();
	
    // Correction valorisation FIDES
	// Les factures avec ATU, FFM, SE, Dxx, APE, AP2 et FPI ne sont pas valorisées FIDES et restent valorisées par OVALIDE
    // Le flag valorise_fides est parfois mal renseignés sur ces factures, il faut le mettre à 0
	if ($ENV_TYPEETS != "1") {
		$sqlcmd = "
					INSERT INTO pmsi.t_divers (code, texte, valeur, description, valeur_date)
					SELECT
						'FIDES_ACE_DATE',
						'Date de passage à FIDES ACE',
						'31/12/2099',
						'Date de passage à FIDES ACE',
						'2099-12-31'::date
					WHERE 'FIDES_ACE_DATE' NOT IN (SELECT code FROM pmsi.t_divers);
					";
		$toResult = execute_sql($sqlcmd, $nbE, $nbW );
					
		$sqlcmd = "	WITH 
					w_except AS (
						SELECT 
                            DISTINCT rss_id 
                        FROM 
                            temp.p_rsf_detail 
                        WHERE 
                             prestation_id = ANY(ARRAY(SELECT to_id FROM pmsi.v_listes_contenu_1 WHERE liste_code = 'CTI_XFIDESACE')::bigint[])
					),
					w_prestations AS (
						SELECT array_agg(to_id) as ngap_array FROM pmsi.v_listes_contenu_1 WHERE liste_code IN ('CTI_NGAP_P', 'CTI_CCAM_P')
					),
					w_fides AS (
						SELECT
							p_rsf_total.rss_id as w_rss_id
							,CASE WHEN ghm_id = 0 AND w_except.rss_id IS NULL AND p_rss.date_sortie >= t_divers.valeur_date AND array_agg(distinct p_rsf_detail.prestation_id) && ngap_array THEN 1 ELSE 0 END as w_valorise_fides
						FROM
							temp.p_rsf_total
							LEFT JOIN temp.p_rsf_detail ON p_rsf_total.rss_id = p_rsf_detail.rss_id
							LEFT JOIN temp.p_rss ON p_rss.oid = p_rsf_total.rss_id
                            LEFT JOIN w_except ON w_except.rss_id = p_rss.oid
							JOIN pmsi.t_divers ON t_divers.code = 'FIDES_ACE_DATE',
							w_prestations
						GROUP BY p_rsf_total.rss_id, p_rss.ghm_id, p_rss.date_sortie, ngap_array, t_divers.valeur_date, w_except.rss_id
					)
					UPDATE temp.p_rsf_total SET 
						valorise_fides = w_valorise_fides
					FROM w_fides
					WHERE 1=1
						AND w_fides.w_rss_id = p_rsf_total.rss_id
						AND p_rsf_total.valorise_fides IS DISTINCT FROM w_valorise_fides";
		$toResult = execute_sql($sqlcmd, $nbE, $nbW );	
		commit_trans();
		
		// MAJ p_rsf_detail.fides_detail d'après valorise_fides de p_rsf_total
				$sqlcmd = "UPDATE temp.p_rsf_detail
					SET fides_detail = p_rsf_total.valorise_fides
					FROM temp.p_rsf_total
					WHERE p_rsf_total.rss_id = p_rsf_detail.rss_id AND
						p_rsf_total.valorise_fides IS NOT NULL AND
						fides_detail IS DISTINCT FROM p_rsf_total.valorise_fides AND
						prestation_id <> ALL(SELECT t_prestations.oid FROM pmsi.t_prestations WHERE code = 'MOPHNG');";
		$toResult = execute_sql($sqlcmd, $nbE, $nbW );	
		commit_trans();
		
		$sqlcmd = "UPDATE temp.p_rsf_detail
					SET fides_detail = 0
					FROM pmsi.t_prestations
					WHERE t_prestations.oid = prestation_id AND
						t_prestations.code = 'MOPHNG' AND
						fides_detail IS DISTINCT FROM '0'";
		$toResult = execute_sql($sqlcmd, $nbE, $nbW );
		commit_trans();
	}
    
    
    if ($ENV_TYPEETS != "1") {
        generation_valoace();
    }

    // Type traitement = IVG ou SU
    if ($ENV_TYPEETS != "1") {
    
        // Traitement epmsi (AMO ou AME)
        $sqlcmd = "UPDATE temp.p_rss
                SET traitement_epmsi = '32'
                FROM temp.p_rsf_total
                JOIN base.t_pec ON code_pec_id = t_pec.oid 
                JOIN base.t_motif_non_facturation ON motif_non_facturation_id = t_motif_non_facturation.oid
                WHERE p_rss.oid = p_rsf_total.rss_id AND
                    traitement_epmsi = '13' AND
                    p_rss.ghm_id IN (SELECT oid FROM pmsi.t_ghm WHERE code = '14Z08Z') AND
                    (
                    t_pec.code IN ('1','2') OR
                    t_pec.code = '0' AND
                    t_motif_non_facturation.code = '1'
                    )                    
                    ;";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
        commit_trans();
    
        // Traitement epmsi (SU)
        // CF chapitre "valorisation SU" du manuel de VisualValoSej
        // Les séjours en SU sont repérés à partir des variables
        // . Séjour facturable à l'AM codée à 0
        // . Motif de non facturation à l'AM codé à 4
        // . Les IVG (traitement ePMSI = '32') sont hors champ
        $sqlcmd = "UPDATE temp.p_rss
                SET traitement_epmsi = '33'
                FROM temp.p_rsf_total
                    JOIN base.t_pec ON code_pec_id = t_pec.oid 
                    JOIN base.t_motif_non_facturation ON motif_non_facturation_id = t_motif_non_facturation.oid
                WHERE 1=1
                    AND p_rss.oid = p_rsf_total.rss_id
                    AND t_pec.code = '0'
                    AND t_motif_non_facturation.code = '4'
                    AND traitement_epmsi IN ('30', '24')
                    ;";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
        commit_trans();
    }
    
    // Valorisation AME (spécial public)
    if ($ENV_TYPEETS != "1") {
    
        // Traitement epmsi
        $sqlcmd = "UPDATE temp.p_rss
                SET traitement_epmsi = '31'
                FROM temp.p_rsf_total
                JOIN base.t_motif_non_facturation ON motif_non_facturation_id = t_motif_non_facturation.oid 
                JOIN base.t_pec ON code_pec_id = t_pec.oid 
                WHERE p_rss.oid = p_rsf_total.rss_id AND
                    traitement_epmsi = '24' AND
                    t_pec.code = '0' AND
                    t_motif_non_facturation.code = '1' AND
                    ghm_id <> 0 ;";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
        commit_trans();
        
        // valorisation ghs = 80% base remboursement * 1,2 (soit 1,056)
        // Pas d'application du taux de remboursement
        $sqlcmd = "UPDATE temp.p_rsf_detail
                SET taux_remboursement = 80,
                    coefficient_mco = p_rsf_detail.coefficient_geo * 
                        ( CASE WHEN t_prestations.code IN ('GHS', 'EXH') THEN 0.8 ELSE 1 END )
                       *
                        CASE 
                            WHEN p_rss.date_sortie >= t_finess.date_debut_coefficient_pacte_resp_9 THEN t_finess.coefficient_pacte_resp_9 
                            WHEN p_rss.date_sortie >= t_finess.date_debut_coefficient_pacte_resp_8 THEN t_finess.coefficient_pacte_resp_8 
                            WHEN p_rss.date_sortie >= t_finess.date_debut_coefficient_pacte_resp_7 THEN t_finess.coefficient_pacte_resp_7 
                            WHEN p_rss.date_sortie >= t_finess.date_debut_coefficient_pacte_resp_6 THEN t_finess.coefficient_pacte_resp_6 
                            WHEN p_rss.date_sortie >= t_finess.date_debut_coefficient_pacte_resp_5 THEN t_finess.coefficient_pacte_resp_5 
                            WHEN p_rss.date_sortie >= t_finess.date_debut_coefficient_pacte_resp_4 THEN t_finess.coefficient_pacte_resp_4 
                            WHEN p_rss.date_sortie >= t_finess.date_debut_coefficient_pacte_resp_3 THEN t_finess.coefficient_pacte_resp_3 
                            WHEN p_rss.date_sortie >= t_finess.date_debut_coefficient_pacte_resp_2 THEN t_finess.coefficient_pacte_resp_2 
                            WHEN p_rss.date_sortie >= t_finess.date_debut_coefficient_pacte_resp_1 THEN t_finess.coefficient_pacte_resp_1 
                            ELSE 1::numeric 
                        END,
                    coefficient_geo = p_rsf_detail.coefficient_geo  * (CASE WHEN t_prestations.code IN ('GHS', 'EXH') THEN 0.8 ELSE 1 END ),
                    update_rules = array_append(update_rules, 44)
                FROM temp.p_rss,
                    pmsi.t_prestations,
                    base.t_finess
                WHERE p_rss.oid = p_rsf_detail.rss_id AND
                    p_rss.finess = t_finess.code AND
                    traitement_epmsi = '31' AND 
                    import_id = $import_id AND 
                    ghm_id <> 0 AND
                    prestation_id = t_prestations.oid AND
                    t_prestations.code IN ('GHS','EXH','ANT','SRC','STF','REA','NN1','NN2','NN3','REP','RAP','SDC') AND p_rsf_detail.base_remboursement <> 0 AND
                    est_ligne_rss = '1'";
        $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
        commit_trans();

    }

    // Base de remboursement hors coefficient MCO, hors AME : nombre * prix_unitaire * coefficient, arrondi à 3 décimales
    $sqlcmd = "UPDATE temp.p_rsf_detail 
            SET base_remboursement_sauf_transition_sauf_ame = round(nombre * prix_unitaire * coefficient, 3),
                update_rules = array_append(update_rules, 50)
            FROM
                base.t_finess, temp.p_rss, pmsi.t_prestations
            WHERE 1=1
                AND p_rss.oid = p_rsf_detail.rss_id
                AND p_rss.finess = t_finess.code
                AND p_rsf_detail.est_ligne_rss = '1' 
                AND p_rsf_detail.prestation_id = t_prestations.oid
                AND (prix_unitaire <> 0 AND nombre > 0 AND coefficient <> 0 OR t_prestations.code = 'LIM_SRC')
                AND base_remboursement_sauf_transition_sauf_ame != round(nombre * prix_unitaire * coefficient, 3);";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    logInfoMsg("Sous totaux RSF");
    $sqlcmd = "UPDATE temp.p_rsf_total 
                SET base_remboursement = COALESCE(subview.base_remboursement,0)
                FROM temp.p_rss 
                LEFT JOIN (
                    SELECT rss_id, 
                    SUM(p_rsf_detail.base_remboursement) as base_remboursement 
                    FROM temp.p_rsf_detail 
                    WHERE p_rsf_detail.est_ligne_rss = '1' 
                    GROUP BY rss_id) subview ON p_rss.oid = subview.rss_id
                WHERE import_id = $import_id AND
                    p_rsf_total.rss_id = p_rss.oid AND  
                    (
                        p_rsf_total.base_remboursement IS DISTINCT FROM  COALESCE(subview.base_remboursement,0)
                    )";
    
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    
    commit_trans();
    
    
    $sqlcmd = "UPDATE temp.p_rsf_total SET 
                    t2a_facture = COALESCE(subview.t2a_facture,0), 
                    dmi_facture = COALESCE(subview.dmi_facture,0), 
                    phc_facture = COALESCE(subview.phc_facture,0),
                    forfait_facture = COALESCE(subview.forfait_facture,0),
                    nb_exh = COALESCE(subview.nb_exh,0),
                    ca_exh = COALESCE(subview.ca_exh,0),
                    nb_exb = COALESCE(subview.nb_exb,0),
                    ca_exb = COALESCE(subview.ca_exb,0),
                    nb_ghs = COALESCE(subview.nb_ghs,0),
                    ca_ghs = COALESCE(subview.ca_ghs,0)
                FROM temp.p_rss
                LEFT JOIN 
                    ( 
                    SELECT rss_id,  
                        SUM(CASE WHEN t_prestations.section_code[9] LIKE 'S1%' THEN p_rsf_detail.base_remboursement ELSE 0 END) as t2a_facture,  
                        SUM(CASE WHEN t_prestations.section_code[9] LIKE 'S2%' THEN p_rsf_detail.base_remboursement ELSE 0 END) as dmi_facture,  
                        SUM(CASE WHEN t_prestations.section_code[9] LIKE 'S3%' THEN p_rsf_detail.base_remboursement ELSE 0 END) as phc_facture, 
                        
                        SUM(CASE WHEN t_prestations.code = 'EXH' THEN p_rsf_detail.nombre ELSE 0 END) as nb_exh,  
                        SUM(CASE WHEN t_prestations.code = 'EXH' THEN p_rsf_detail.base_remboursement ELSE 0 END) as ca_exh, 
                        SUM(CASE WHEN t_prestations.code = 'GHS' AND coefficient < 1 THEN p_rsf_detail.nombre ELSE 0 END) as nb_exb,  
                        SUM(CASE WHEN t_prestations.code = 'GHS' AND coefficient < 1 THEN p_rsf_detail.base_remboursement ELSE 0 END) as ca_exb, 
                        SUM(CASE WHEN t_prestations.code = 'GHS' THEN p_rsf_detail.nombre ELSE 0 END) as nb_ghs,  
                        SUM(CASE WHEN t_prestations.code = 'GHS' THEN p_rsf_detail.base_remboursement ELSE 0 END) as ca_ghs,
                        SUM(CASE WHEN t_prestations.section_code[9] LIKE 'S13%' THEN p_rsf_detail.base_remboursement ELSE 0 END) as forfait_facture 
                    FROM temp.p_rsf_detail
                        JOIN pmsi.t_prestations ON p_rsf_detail.prestation_id =  t_prestations.oid
                    WHERE p_rsf_detail.type = 'B' AND p_rsf_detail.est_ligne_rss = '1' 
                    GROUP BY rss_id) subview ON p_rss.oid = subview.rss_id
                WHERE p_rsf_total.rss_id = p_rss.oid AND p_rss.import_id = $import_id ";
    
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    
    commit_trans();

    // Correction EXB
    $sqlcmd = "UPDATE temp.p_rsf_total SET 
            nb_exb = subview.nb_exb, 
            ca_exb = subview.ca_exb 
            FROM 
                temp.p_rss, 
                ( 
                    SELECT 
                        rss_id,  
                        SUM(CASE WHEN t_prestations.code = 'GHS' AND coefficient < 1 THEN p_rsf_detail.nombre ELSE 0 END) as nb_exb,  
                        SUM(CASE WHEN t_prestations.code = 'GHS' AND coefficient < 1 THEN p_rsf_detail.base_remboursement ELSE 0 END) as ca_exb 
                    FROM 
                        temp.p_rsf_detail,
                        pmsi.t_prestations
                    WHERE 
                        p_rsf_detail.prestation_id =  t_prestations.oid 
                        AND p_rsf_detail.type = 'B' 
                        AND p_rsf_detail.est_ligne_rss = '1' 
                    GROUP BY rss_id
                ) subview 
            WHERE 
                p_rsf_total.rss_id = p_rss.oid 
                AND p_rsf_total.rss_id = subview.rss_id 
                AND p_rsf_total.rss_id IN 
                                        ( SELECT 
                                                rss_id 
                                            FROM 
                                                temp.p_rsf_detail, 
                                                pmsi.t_prestations 
                                            WHERE 
                                                p_rsf_detail.prestation_id =  t_prestations.oid 
                                                AND t_prestations.code = 'GHS' 
                                                AND coefficient > 0 AND coefficient < 1
                                        );
                ";
    
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();

    // CA Théorique
    $sqlcmd = "UPDATE temp.p_rsf_total SET ca_ghs_theorique = subview.ca_ghs_theorique 
            FROM temp.p_rss,  
            (  
            SELECT rss_id, SUM(CASE WHEN coefficient >= 1 THEN p_rsf_detail.base_remboursement WHEN coefficient > 0 THEN round(prix_unitaire * nombre * coefficient_mco,2) ELSE 0 END) as ca_ghs_theorique  
            FROM temp.p_rsf_detail  
            WHERE p_rsf_detail.type = 'B' AND p_rsf_detail.est_ligne_rss = '1' AND p_rsf_detail.prestation_id IN (SELECT oid FROM pmsi.t_prestations WHERE code = 'GHS')  
            GROUP BY rss_id  
            ) subview  
            WHERE p_rsf_total.rss_id = p_rss.oid AND p_rss.import_id = $import_id AND p_rsf_total.rss_id = subview.rss_id AND p_rsf_total.ca_ghs_theorique <> subview.ca_ghs_theorique ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    $sqlcmd = "UPDATE temp.p_rsf_total 
            SET ca_ghs_theorique = p_rsf_total.ca_ghs  
            FROM temp.p_rss  
            WHERE p_rsf_total.rss_id = p_rss.oid AND p_rss.import_id = $import_id 
                AND ((p_rsf_total.ca_ghs_theorique = 0 AND p_rsf_total.ca_ghs <> 0) OR p_rsf_total.ca_ghs_theorique IS NULL); ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    // Reprise des cumuls dans p_rss
    logInfoMsg("Report des cumuls RSS");
    $sqlcmd = "UPDATE temp.p_rss 
            SET base_remboursement = p_rsf_total.base_remboursement, 
                sejour_facture = p_rsf_total.sejour_facture, 
                honoraires_factures = p_rsf_total.honoraires_factures, 
                t2a_facture = p_rsf_total.t2a_facture, 
                dmi_facture = p_rsf_total.dmi_facture, 
                phc_facture = p_rsf_total.phc_facture, 
                ca_ghs_theorique = p_rsf_total.ca_ghs_theorique, 
                nb_ghs = p_rsf_total.nb_ghs, 
                ca_ghs = p_rsf_total.ca_ghs, 
                nb_exb = p_rsf_total.nb_exb, 
                ca_exb = p_rsf_total.ca_exb, 
                nb_exh = p_rsf_total.nb_exh, 
                ca_exh = p_rsf_total.ca_exh,
                forfait_facture = p_rsf_total.forfait_facture,
                nb_ghsmin = p_rsf_total.nb_ghsmin
            FROM temp.p_rsf_total 
            WHERE p_rss.oid = p_rsf_total.rss_id AND 
                p_rss.import_id = $import_id;";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();
    
    // Recherche des factures inexistantes
    logInfoMsg("Recherche des en-têtes de factures manquants");
    
    $sqlcmd = " SELECT 
                    p_rss.no_rss
                FROM
                    temp.p_rss
                    LEFT JOIN temp.p_rsf_total ON p_rsf_total.rss_id = p_rss.oid
                WHERE 1=1
                    AND p_rsf_total.rss_id IS NULL
                    AND p_rss.import_id = $import_id";
    $toResult = execute_sql($sqlcmd);
    if (is_resource($toResult)) {
        while ($row = pg_fetch_array($toResult)) {
            logWarnMsg("Aucun en-tête de facture trouvé pour le RSS n°" . $row[0] . ". Un en-tête vide sera créé.");
        } 
    }
    
    // Création des factures inexistantes
    $sqlcmd = " INSERT INTO temp.p_rsf_total(
                    finess, no_rss, code_pec, rang_beneficiaire, regime, nature_pec,
                    justificatif_exo, no_facture, code_regularisation, base_remboursement,
                    sejour_facture, sejour_remboursable, honoraires_factures, honoraires_remboursable,
                    t2a_facture, dmi_facture, phc_facture, participation_assure_avant_oc,
                    sejour_remboursable_2, honoraires_remboursable_2, montant_dmi_ghs2006,
                    forfait_facture,
                    nb_exh, ca_exh, nb_exb, ca_exb, nb_ghs, ca_ghs, taux_remboursement, regime_id, exoneration_tm_id, nature_pec_id, code_pec_id, rss_id, nb_ghsmin)
                SELECT
                    finess, no_rss, '1', '', '01', '10', '', '', '', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 0, 0, oid, 0
                FROM temp.p_rss
                WHERE
                    import_id = $import_id
                    AND oid NOT IN (SELECT rss_id FROM temp.p_rsf_total)";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );  
    commit_trans();
	
	
	// Mise a jour des dates EXH
	$sqlcmd = "UPDATE temp.p_rsf_detail
				SET date_debut = date_debut_new
				FROM
				(
				SELECT rss_id, prestation_id, date_debut, date_fin, nombre, date(date_sortie - (nombre||' days')::interval) AS date_debut_new
				FROM temp.p_rsf_detail
				JOIN pmsi.t_prestations on prestation_id = t_prestations.oid
				JOIN temp.p_rss ON rss_id = p_rss.oid
				WHERE t_prestations.code = 'EXH' AND 
					date_debut = date_entree AND
					date(date_sortie - (nombre||' days')::interval) > date_entree
				) subview
				WHERE p_rsf_detail.rss_id = subview.rss_id AND
					p_rsf_detail.prestation_id = subview.prestation_id AND
					p_rsf_detail.date_debut = subview.date_debut AND
					p_rsf_detail.date_fin = subview.date_fin AND
					p_rsf_detail.nombre = subview.nombre
				;";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );  
    commit_trans();

    logInfoMsg("FIN TRAITEMENTS COMPLEMENTAIRES RSF. $nbE erreurs.");
    
}



function generation_validation_tables() {

    logInfoMsg("VALIDATION TABLES");
    
    
    begin_trans();
    
    $nbE = 0;
    
    logInfoMsg("Suppression index");
    
    disable_index("i_rss_1");
    disable_index("i_rss_2");
    disable_index("i_rss_3");
    disable_index("i_rss_4");
    disable_index("i_rss_5");
    disable_index("i_rss_6");
    disable_index("i_rss_7");
    disable_index("i_rss_8");
    disable_index("i_rss_9");
    disable_index("i_rss_10");
    disable_index("i_rss_11");
    disable_index("i_rss_12");
    disable_index("i_rss_13");
    disable_index("i_rss_14");
    disable_index("i_rss_16");
    disable_index("i_rss_17");
    disable_index("i_rss_18");
    disable_index("i_rss_19");
    disable_index("i_rss_20");
    disable_index("i_rss_21");
    
    disable_index("i_identites_1");
    disable_index("i_identites_3");
    
    disable_index("i_rss_rum_1");
    disable_index("i_rss_rum_4");
    disable_index("i_rss_rum_5");
    disable_index("i_rss_rum_6");
    disable_index("i_rss_rum_7");
    disable_index("i_rss_rum_8");
    disable_index("i_rss_rum_9");
    disable_index("i_rss_rum_10");
    disable_index("i_rss_rum_11");
    disable_index("i_rss_rum_12");
    disable_index("i_rss_rum_13");

    disable_index("i_rss_diagnostics_1");
    disable_index("i_rss_diagnostics_2");
    disable_index("i_rss_diagnostics_3");
    disable_index("i_rss_diagnostics_7");
    
    disable_index("i_rsf_total_1");
    disable_index("i_rsf_total_3");
    
    disable_index("i_rsf_detail_1");
    disable_index("i_rsf_detail_2");
    disable_index("i_rsf_detail_5");
    
    disable_index("i_rss_actes_1");
    disable_index("i_rss_actes_2");
    disable_index("i_rss_actes_3");
    disable_index("i_rss_actes_4");
    disable_index("i_rss_actes_5");
    disable_index("i_rss_actes_9");
    
    disable_index("i_rss_lpp_1");
    disable_index("i_rss_lpp_2");
    disable_index("i_rss_lpp_3");
    
    disable_index("i_rss_ucd_1");
    disable_index("i_rss_ucd_2");
    disable_index("i_rss_ucd_3");

    disable_index("i_rss_leg_1");
    disable_index("i_rss_leg_2");
    disable_index("i_rss_leg_3");

    
    commit_trans();
    
    
    logInfoMsg("Ajout des données");
    
    
    $sqlcmd = "INSERT INTO pmsi.p_identites SELECT * FROM temp.p_identites";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();
    
    $sqlcmd = "INSERT INTO pmsi.p_rss SELECT * FROM temp.p_rss";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();
    $sqlcmd = "SELECT * FROM setval('pmsi.s_rss'::regclass, COALESCE((SELECT MAX(oid) FROM pmsi.p_rss),0) + 1)";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();
    
    $sqlcmd = "INSERT INTO pmsi.p_rss_rum SELECT * FROM temp.p_rss_rum";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();
        
    $sqlcmd = "INSERT INTO pmsi.p_rss_actes SELECT * FROM temp.p_rss_actes";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();
    
    $sqlcmd = "INSERT INTO pmsi.p_rss_diagnostics SELECT * FROM temp.p_rss_diagnostics";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();
    
    $sqlcmd = "INSERT INTO pmsi.p_rss_lpp SELECT * FROM temp.p_rss_lpp";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();
    
    $sqlcmd = "INSERT INTO pmsi.p_rss_ucd SELECT * FROM temp.p_rss_ucd";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();
    
    $sqlcmd = "INSERT INTO pmsi.p_rss_leg SELECT * FROM temp.p_rss_leg";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();
    
    $sqlcmd = "INSERT INTO pmsi.p_rss_maternite SELECT * FROM temp.p_rss_maternite";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();
    
    $sqlcmd = "INSERT INTO pmsi.p_ctl_mt2a SELECT * FROM temp.p_ctl_mt2a";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();
    
    $sqlcmd = "INSERT INTO pmsi.p_vidhosp SELECT * FROM temp.p_vidhosp";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();
    
    $sqlcmd = "INSERT INTO pmsi.p_vidhosp_crc SELECT * FROM temp.p_vidhosp_crc";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();
    
    $sqlcmd = "INSERT INTO pmsi.p_rsa SELECT * FROM temp.p_rsa";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();
    
    $sqlcmd = "INSERT INTO pmsi.p_rsa_rdth SELECT * FROM temp.p_rsa_rdth";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();
        
    $sqlcmd = "INSERT INTO pmsi.p_rsf_total SELECT * FROM temp.p_rsf_total";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();
    
    $sqlcmd = "INSERT INTO pmsi.p_rsf_detail SELECT * FROM temp.p_rsf_detail";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();
    
    $sqlcmd = "INSERT INTO pmsi.p_rsf_detail_non_valorise SELECT * FROM temp.p_rsf_detail_non_valorise";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();
	
    $sqlcmd = "INSERT INTO pmsi.p_fichsup_transports SELECT * FROM temp.p_fichsup_transports";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();

	
	$sqlcmd = "
		INSERT INTO pmsi.p_rss_transferts (rss_id, etablissement_provenance_id,  etablissement_destination_id) 
		SELECT rss_id, MAX(etablissement_provenance_id), MAX(etablissement_destination_id) 
		FROM temp.p_rss_transferts w_transferts
        WHERE NOT EXISTS (
            SELECT 1 FROM pmsi.p_rss_transferts
            WHERE w_transferts.rss_id = p_rss_transferts.rss_id
            )
		GROUP BY 1
		";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );  
    commit_trans();
    
    logInfoMsg("Recréation index");
    
    enable_index("i_rss_1");
    enable_index("i_rss_2");
    enable_index("i_rss_3");
    enable_index("i_rss_4");
    enable_index("i_rss_5");
    enable_index("i_rss_6");
    enable_index("i_rss_7");
    enable_index("i_rss_8");
    enable_index("i_rss_9");
    enable_index("i_rss_10");
    enable_index("i_rss_11");
    enable_index("i_rss_12");
    enable_index("i_rss_13");
    enable_index("i_rss_14");
    enable_index("i_rss_16");
    enable_index("i_rss_17");
    enable_index("i_rss_18");
    enable_index("i_rss_19");
    enable_index("i_rss_20");
    enable_index("i_rss_21");
    
    enable_index("i_identites_1");
    enable_index("i_identites_3");
    
    enable_index("i_rss_rum_1");
    enable_index("i_rss_rum_4");
    enable_index("i_rss_rum_5");
    enable_index("i_rss_rum_6");
    enable_index("i_rss_rum_7");
    enable_index("i_rss_rum_8");
    enable_index("i_rss_rum_9");
    enable_index("i_rss_rum_10");
    enable_index("i_rss_rum_11");
    enable_index("i_rss_rum_12");
    enable_index("i_rss_rum_13");
    
    enable_index("i_rss_diagnostics_1");
    enable_index("i_rss_diagnostics_2");
    enable_index("i_rss_diagnostics_3");
    enable_index("i_rss_diagnostics_6");
    enable_index("i_rss_diagnostics_7");
    
    
    enable_index("i_rsf_total_1");
    enable_index("i_rsf_total_3");
    
    enable_index("i_rsf_detail_1");
    enable_index("i_rsf_detail_2");
    enable_index("i_rsf_detail_5");
    
    enable_index("i_rss_actes_1");
    enable_index("i_rss_actes_2");
    enable_index("i_rss_actes_3");
    enable_index("i_rss_actes_4");
    enable_index("i_rss_actes_5");
    enable_index("i_rss_actes_8");
    enable_index("i_rss_actes_9");
    
    enable_index("i_rss_lpp_1");
    enable_index("i_rss_lpp_2");
    enable_index("i_rss_lpp_3");
    enable_index("i_rss_lpp_6");
    
    enable_index("i_rss_ucd_1");
    enable_index("i_rss_ucd_2");
    enable_index("i_rss_ucd_3");
    enable_index("i_rss_ucd_6");
    
    enable_index("i_rss_leg_1");
    enable_index("i_rss_leg_2");
    enable_index("i_rss_leg_3");
    
    commit_trans();
    
    logInfoMsg("FIN VALIDATION TABLES. $nbE erreurs.");

}


function generation_traitements_finaux() {

    global $import_id;
    global $omitExpert;


    logInfoMsg("TRAITEMENTS FINAUX");

    begin_trans();
    
    // Traitement des simulations afin de ne pas faire sauter le lien rss_id entre les tables de simulations et pmsi.p_rss et autres tables du pmsi

    $simulations = array(
                'p_simulation_fg2021'              =>  '2020' ,
                'p_simulation_fg2122'              =>  '2021' ,
                'p_simulation_fg2223'              =>  '2022' ,
                'p_simulation_fg2324'              =>  '2023' ,
                'p_simulation_fg2425'              =>  '2024' ,
                'p_simulation_fg2526'              =>  '2025' ,
                'p_simulation_fg2627'              =>  '2026' 
                )
                ;

    foreach ($simulations as $table_sim => $date) {

        $sql = "
            SELECT *
            FROM information_schema.tables
            WHERE 1=1
                AND table_schema = 'pmsi'
                AND table_name = '" . $table_sim . "'
        ";
        
        $res = execute_sql($sql);
        if (pg_num_rows($res) > 0) {

            logInfoMsg("Mise à jour des oid pour simulation table : $table_sim");

            $sqlcmd = "     
        
                UPDATE pmsi.$table_sim 
                SET rss_id = p_rss.oid
                FROM pmsi.p_rss
                WHERE 1=1
                    AND $table_sim .no_rss = p_rss.no_rss 
                    AND p_rss.date_sortie BETWEEN  ($date::text || '0301')::date AND ($date::text || '1231')::date
                    AND $table_sim.annee_sortie = $date::text
                    AND $table_sim.rss_id <> p_rss.oid
                ;

                UPDATE pmsi.$table_sim 
                SET rss_id = p_rss.oid
                FROM pmsi.p_rss
                WHERE 1=1
                    AND $table_sim .no_rss = p_rss.no_rss 
                    AND p_rss.date_sortie BETWEEN (($date::int + 1)::text ||'0101')::date AND (( to_date( ($date::int + 1)::text || '0301' , 'YYYYMMDD') - 1 )::text)::date
                    AND $table_sim.annee_sortie = ($date::int + 1)::text
                    AND $table_sim.rss_id <> p_rss.oid
                ;
            ";
                    
            $toResult = execute_sql($sqlcmd);
            commit_trans();

        } 
    }
	
	logInfoMsg("Mise à jour des oid pour fiche n°5");
	$sqlcmd = "
		UPDATE pmsi.p_fiche5_rss SET
			rss_id = p_rss.oid
		FROM pmsi.t_fiche5_enquete
		JOIN pmsi.p_rss ON
			p_rss.ghm_id > 0 AND
			p_rss.en_cours = '0' AND
			date_part('year',p_rss.date_sortie) = t_fiche5_enquete.annee
		WHERE p_fiche5_rss.no_rss = p_rss.no_rss AND
			p_fiche5_rss.rss_id IS DISTINCT FROM p_rss.oid
		;";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();


    $nbE = 0;
    
    logInfoMsg("Initialisation patients");
    
    
    logInfoMsg("Initialisation RSS sans nom");
    $sqlcmd = "INSERT into pmsi.p_identites (no_rss, nom, finess, rss_id) 
            SELECT p_rss.no_rss, 'RSS ' || p_rss.no_rss, p_rss.finess, p_rss.oid 
            FROM pmsi.p_rss  
            LEFT JOIN pmsi.p_identites ON (p_rss.oid = p_identites.rss_id) 
            WHERE p_identites.rss_id IS NULL";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();

    
    $sqlcmd = "UPDATE pmsi.p_identites SET prenom = '' WHERE prenom is null";
    $toResult = execute_sql($sqlcmd);
    commit_trans();
    
    vacuum_table("p_patients");
    vacuum_table("p_identites");
    vacuum_table("p_rss");
    
    logInfoMsg("Maintenance des patients");
    
    // Lien activite / pmsi
    if (file_exists("../../activite/settings.xml")) {
    
        // Créer une table d'association dans activité
        $sqlcmd = "SELECT activite.cti_reorganize_sejour_pmsi()";
        //$toResult = execute_sql($sqlcmd);
        //commit_trans();
        
        // Récupérer les noms activité vers le PMSI
        $sqlcmd = "UPDATE pmsi.p_identites
            SET 
                nom = p_patients.nom,
                nom_naissance = p_patients.nom_naissance,
                prenom = p_patients.prenom
            FROM pmsi.p_rss,
                activite.p_sejour_pmsi
                JOIN activite.p_sejours ON p_sejour_pmsi.no_sejour = p_sejours.no_sejour
                JOIN activite.p_patients ON p_sejours.no_patient = p_patients.no_patient
            WHERE p_rss.oid = p_identites.rss_id AND
                p_identites.nom LIKE 'RSS %' AND
                p_sejour_pmsi.pmsi_type = 'MCO' AND
                p_sejour_pmsi.rss_id = p_rss.oid;";
        $toResult = execute_sql($sqlcmd);
        commit_trans();
    }
    
    $sqlcmd = "UPDATE pmsi.p_rss SET patient_id = 0 FROM  
        pmsi.p_identites, pmsi.p_patients  
        WHERE p_rss.oid = p_identites.rss_id  
        AND p_patients.oid = p_rss.patient_id 
        AND p_rss.patient_id <> 0  
        AND (upper(translate(p_identites.nom || p_identites.prenom, ' -', '')) || '|'::text ||  p_rss.date_naissance::text || '|'::text ||  p_rss.sexe::text)   
        <> (upper(translate(p_patients.nom || p_patients.prenom, ' -', '')) || '|'::text ||  p_patients.date_naissance::text || '|'::text ||  p_patients.sexe::text) ";
    $toResult = execute_sql($sqlcmd);
    
    commit_trans();
    
    $sqlcmd = "DROP TABLE IF EXISTS temp_pmsi_identites ;";
    $toResult = execute_sql($sqlcmd);
    commit_trans();

    $sqlcmd = "CREATE TEMP TABLE temp_pmsi_identites (finess character(9), nom character varying(255), prenom character varying(255), nomprenom character varying(255), date_naissance date, sexe character(1));";
    $toResult = execute_sql($sqlcmd);
    commit_trans();

    $sqlcmd = "INSERT INTO temp_pmsi_identites(finess, nom, prenom, nomprenom, date_naissance, sexe)
        SELECT DISTINCT p_rss.finess, p_identites.nom, p_identites.prenom, upper(translate(p_identites.nom || p_identites.prenom, ' -', '')) AS nomprenom, p_rss.date_naissance, p_rss.sexe
        FROM pmsi.p_rss, pmsi.p_identites 
        WHERE p_rss.oid = p_identites.rss_id AND (p_rss.patient_id IS NULL OR p_rss.patient_id = 0);";
    $toResult = execute_sql($sqlcmd);
    commit_trans();


    $sqlcmd = "INSERT INTO pmsi.p_patients (finess, nom, prenom, date_naissance, sexe)
    SELECT temp_pmsi_identites.finess, temp_pmsi_identites.nom, temp_pmsi_identites.prenom, temp_pmsi_identites.date_naissance, temp_pmsi_identites.sexe FROM temp_pmsi_identites 
    LEFT JOIN pmsi.p_patients ON (
        temp_pmsi_identites.nomprenom = upper(translate(p_patients.nom || p_patients.prenom, ' -', ''))
        AND temp_pmsi_identites.date_naissance = p_patients.date_naissance
        AND temp_pmsi_identites.sexe = p_patients.sexe)
    WHERE p_patients.nom IS NULL";
    $toResult = execute_sql($sqlcmd);
    commit_trans();

    $sqlcmd = "UPDATE pmsi.p_patients SET no_patient = 0 - nextval('pmsi.s_no_interne_patients'::regclass) WHERE no_patient = 0 OR no_patient IS NULL; ";
    $toResult = execute_sql($sqlcmd);
    
    commit_trans();
    
    $sqlcmd = "UPDATE pmsi.p_rss SET patient_id = p_patients.oid  
        FROM pmsi.p_identites, pmsi.p_patients  
        WHERE p_rss.oid = p_identites.rss_id 
        AND COALESCE(p_rss.patient_id,0) = 0 
        AND p_rss.date_naissance = p_patients.date_naissance 
        AND p_rss.sexe = p_patients.sexe 
        AND upper(translate(p_identites.nom || p_identites.prenom, ' -', '')) = upper(translate(p_patients.nom || p_patients.prenom, ' -', ''))  ";
    
    $toResult = execute_sql($sqlcmd);
    
    commit_trans();
    
    $sqlcmd = "UPDATE pmsi.p_rss SET patient_id = subview.new_id FROM  
            ( 
            SELECT  
            p_patients.oid AS old_id,  
            p_patients_nouveaux.oid as new_id  
            FROM pmsi.p_patients, pmsi.p_patients p_patients_nouveaux  
            WHERE p_patients.oid < p_patients_nouveaux.oid 
            AND upper(translate(p_patients.nom || p_patients.prenom, ' -', '')) = upper(translate(p_patients_nouveaux.nom || p_patients_nouveaux.prenom, ' -', '')) 
            AND p_patients.date_naissance = p_patients_nouveaux.date_naissance 
            AND p_patients.sexe = p_patients_nouveaux.sexe 
            ) subview  
            WHERE p_rss.patient_id = subview.old_id ";
    
    $toResult = execute_sql($sqlcmd);
    commit_trans();
    $toResult = execute_sql($sqlcmd);
    commit_trans();
    
    $sqlcmd = "DELETE FROM pmsi.p_patients WHERE oid NOT IN (SELECT DISTINCT patient_id FROM pmsi.p_rss)";
    $toResult = execute_sql($sqlcmd);
    commit_trans();
    
    $sqlcmd = "UPDATE pmsi.p_patients SET no_patient = subview.no_patient 
        FROM (SELECT patient_id, MAX(no_patient) as no_patient FROM pmsi.p_rss WHERE no_patient > 0 GROUP BY patient_id) subview
        WHERE p_patients.oid = subview.patient_id AND p_patients.no_patient <> subview.no_patient";
    $toResult = execute_sql($sqlcmd);
    commit_trans();
    
    logInfoMsg("Ventilation par unité médicale");
    
    // La séquence SQL est remplacée par une fonction
    
    $sqlcmd = "SELECT pmsi.cti_ventilation_ca_um()";
    $toResult = execute_sql($sqlcmd);
    commit_trans();

    // Mise a jour des taux de remboursements
    
    logInfoMsg("Mise a jour des taux de remboursements");
        
    
    // Depuis vidhosp
    $sqlcmd = "UPDATE pmsi.p_rsf_total
                SET taux_remboursement = p_vidhosp.taux_remboursement_utilise
            FROM pmsi.p_vidhosp
            WHERE p_rsf_total.rss_id = p_vidhosp.rss_id AND
                p_rsf_total.taux_remboursement IS DISTINCT FROM p_vidhosp.taux_remboursement_utilise;";
    $toResult = execute_sql($sqlcmd);
    commit_trans();
    
    
    // Depuis les prestations (si pas vidhosp)
    $sqlcmd = "UPDATE pmsi.p_rsf_total
                SET taux_remboursement = subview.taux_remboursement
                FROM
                    (SELECT p_rss.oid AS rss_id, subview.taux_remboursement
                    FROM pmsi.p_rss
                        LEFT JOIN pmsi.p_vidhosp ON p_rss.oid = p_vidhosp.rss_id
                        JOIN pmsi.p_rsf_total on p_rss.oid = p_rsf_total.rss_id and en_cours = '0'
                        JOIN
                        (
                            SELECT p_rss.oid AS rss_id, 
                                COALESCE(max(p_rsf_detail.taux_remboursement),0) AS taux_remboursement,
                                MAX(CASE WHEN p_rsf_detail.rss_id IS NULL THEN 0 ELSE 1 END) AS has_rsf
                            FROM pmsi.p_rss
                            LEFT JOIN pmsi.p_rsf_detail ON p_rss.oid = p_rsf_detail.rss_id
                            GROUP BY 1
                        ) subview ON p_rsf_total.rss_id = subview.rss_id
                    WHERE p_rsf_total.taux_remboursement <> subview.taux_remboursement AND 
                        (subview.taux_remboursement <> 0 OR has_rsf = 0) AND 
                        p_vidhosp.rss_id IS NULL
                ) subview 
                WHERE p_rsf_total.rss_id = subview.rss_id;";
    $toResult = execute_sql($sqlcmd);
    commit_trans();
    
    /********************************************************
     *
     *      Mise à jour du GHS dans le RSS
     *
     *******************************************************/
     
    logInfoMsg("Mise à jour du GHS dans le RSS");
    
    
    
    // Pour tous les séjours hors séances avec un GHM et sans GHS (GHS 0000), le GHM est placé à 9999
    $sqlcmd = "UPDATE pmsi.p_rss SET
                ghs_id = (SELECT oid from pmsi.t_ghs where code = 9999)
                WHERE
                    ghm_id <> 0
                    AND ghs_id = 0
                    AND ghm_id NOT IN (SELECT oid from pmsi.T_ghm where code LIKE '28%');";
    $toResult = execute_sql($sqlcmd);
    commit_trans();
    
    // GHS 9602 pour les séjours de séances 28Z01Z avec GHS 0000
    $sqlcmd = "UPDATE pmsi.p_rss SET
                ghs_id = (SELECT oid from pmsi.t_ghs where code = 9602)
                WHERE
                    ghm_id <> 0
                    AND ghs_id = (SELECT oid from pmsi.t_ghs where code = 0000)
                    AND ghm_id IN (SELECT oid from pmsi.T_ghm where code LIKE '28Z01Z');";
    $toResult = execute_sql($sqlcmd);
    commit_trans();
    
    // GHS 9603 pour les séjours de séances 28Z02Z avec GHS 0000
    $sqlcmd = "UPDATE pmsi.p_rss SET
                ghs_id = (SELECT oid from pmsi.t_ghs where code = 9603)
                WHERE
                    ghm_id <> 0
                    AND ghs_id = (SELECT oid from pmsi.t_ghs where code = 0000)
                    AND ghm_id IN (SELECT oid from pmsi.T_ghm where code LIKE '28Z02Z');";
    $toResult = execute_sql($sqlcmd);
    commit_trans();
    
    // GHS 9604 pour les séjours de séances 28Z03Z avec GHS 0000
    $sqlcmd = "UPDATE pmsi.p_rss SET
                ghs_id = (SELECT oid from pmsi.t_ghs where code = 9604)
                WHERE
                    ghm_id <> 0
                    AND ghs_id = (SELECT oid from pmsi.t_ghs where code = 0000)
                    AND ghm_id IN (SELECT oid from pmsi.T_ghm where code LIKE '28Z03Z');";
    $toResult = execute_sql($sqlcmd);
    commit_trans();
    
    // GHS 9605 pour les séjours de séances 28Z04Z avec GHS 0000, réalisés en dehors d'une UM avec autorisation 22 (centre pour enfants)
    $sqlcmd = "UPDATE pmsi.p_rss SET
                ghs_id = (SELECT oid from pmsi.t_ghs where code = 9605)
                WHERE
                    ghm_id <> 0
                    AND ghs_id = (SELECT oid from pmsi.t_ghs where code = 0000)
                    AND ghm_id IN (SELECT oid from pmsi.T_ghm where code LIKE '28Z04Z')
                    AND unite_medicale_principale_id IN (SELECT oid FROM pmsi.t_unites_medicales
                                    WHERE type_autorisation IS DISTINCT FROM '22');";
    $toResult = execute_sql($sqlcmd);
    commit_trans();
    
    // GHS 9617 pour les séjours de séances 28Z04Z avec GHS 0000, réalisés dans une UM avec autorisation 22 (centre pour enfants)
    $sqlcmd = "UPDATE pmsi.p_rss SET
                ghs_id = (SELECT oid from pmsi.t_ghs where code = 9617)
                WHERE
                    ghm_id <> 0
                    AND ghs_id = (SELECT oid from pmsi.t_ghs where code = 0000)
                    AND ghm_id IN (SELECT oid from pmsi.T_ghm where code LIKE '28Z04Z')
                    AND unite_medicale_principale_id IN (SELECT oid FROM pmsi.t_unites_medicales
                                    WHERE type_autorisation = '22');";
    $toResult = execute_sql($sqlcmd);
    commit_trans();
    
    // Réport du GHS de la mère dans le RSS
    // Dans les RSF détail, on ne sélectionne que les lignes avec un GHS de mise au monde. Dans les lignes qu'il reste, prend le GHS
    // de celle qui présente la base de remboursement la plus élevée (BR de la mère est toujours la plus élevée)
    $sqlcmd = "UPDATE pmsi.p_rss SET
                    ghs_id = subview.ghs_id
                FROM
                    (
                        SELECT 
                            rss_id,
                            (max(Array [base_remboursement, ghs_id])) [2]::BIGINT AS ghs_id
                        FROM 
                            pmsi.p_rsf_detail
                        WHERE
                        p_rsf_detail.ghs_id IN (SELECT to_id FROM pmsi.t_listes_contenu 
                                        JOIN pmsi.t_listes on t_listes.oid = t_listes_contenu.liste_id WHERE code = 'CTI_GHS_NN')
                        GROUP BY 1
                        ORDER BY 1
                    ) subview
                WHERE subview.rss_id = p_rss.oid;";
    $toResult = execute_sql($sqlcmd);
    commit_trans();

    // On récupère le GHS du bébé depuis la facture de la mère
        $sqlcmd = "         
                WITH w_bb AS (
                    SELECT oid as rss_bb_id, rss_mere_id
                    FROM pmsi.p_rss
                    WHERE rss_mere_id <> 0
                    ), w_ghs_bb AS (
                    SELECT rss_bb_id, w_rsf_mere.ghs_id
                    FROM 
                        pmsi.p_rsf_detail w_rsf_mere
                        JOIN w_bb ON rss_mere_id = w_rsf_mere.rss_id
                        JOIN pmsi.t_ghs ON w_rsf_mere.ghs_id = t_ghs.oid
                        JOIN pmsi.t_ghm ON t_ghs.ghm_id = t_ghm.oid
                        WHERE t_ghm.code LIKE '15%'	
                        AND w_rsf_mere.est_ligne_rss = '1'
                    ) 
                    UPDATE pmsi.p_rss
                    SET ghs_id = w_ghs_bb.ghs_id
                    FROM pmsi.t_ghs, w_ghs_bb
                    WHERE t_ghs.oid = p_rss.ghs_id
                    AND p_rss.oid = rss_bb_id
                    AND t_ghs.code = 9999;
                    ";
                    
    $toResult = execute_sql($sqlcmd);
    commit_trans();
    
    // Réport du GHS du bébé dans le RSS si non trouvé dans la facture
    // Pour les séjours dans la CMD 15 qui ont un GHS à 9999, on prend le GHS du GHM

    $sqlcmd = "UPDATE pmsi.p_rss SET
                    ghs_id = subview.ghs_id
                FROM
                    (
                        SELECT 
                            p_rss.oid as rss_id, 
                            ghs_new.oid as ghs_id
                        FROM
                            pmsi.p_rss
                            JOIN pmsi.t_ghm ON t_ghm.oid = p_rss.ghm_id
                            JOIN pmsi.t_ghs ghs_new ON ghs_new.ghm_id = t_ghm.oid
                            JOIN pmsi.t_ghs ghs_ori ON ghs_ori.oid = p_rss.ghs_id
                        WHERE 
                            t_ghm.code like '15%'
                            AND ghs_ori.code = 9999
                    ) subview
                WHERE subview.rss_id = p_rss.oid 
                AND p_rss.ghs_id <> subview.ghs_id;";
    $toResult = execute_sql($sqlcmd);
    commit_trans();
    
    // transformation unités médicales
    $sqlcmd = "SELECT pmsi.cti_transform_um();";
    $toResult = execute_sql($sqlcmd);
    commit_trans();
    $sqlcmd = "SELECT pmsi.cti_transform_um();";
    $toResult = execute_sql($sqlcmd);
    commit_trans();
    
    // Recherche etat dossier (groupage facturation)
    get_etat_dossier();
    
    // Marquage des séjours selon les critères des Indicateurs de Pilotage des Activités de soins autorisés (IPA)
    estampillage_ipa();
    
    // Calcul d'indicateurs de maternité
    set_maternite();
    
    // Traitement des séjours selon prestations SRC
    set_src();

    // Traitement des séjours selon prestations REA
    set_rea();
    
    // Traitement sur les gestes marqueurs
    set_gestes_marqueurs();
    
    // Traitement sur cancero
    set_cancero();

    // Traitement Etude Cardio
    set_etude_cardio();
    
    // Prétraitements études
    set_etudes();
    
    // Calcul d'indicateurs sur les RSS utiles au calcul des indicateurs SAE
    set_sae();
    
    // Execution règles Expert
    if ($omitExpert == false) {
        expert_execute_rules();
    }
    else {
        logInfoMsg("Omission de l'exécution règles EXPERT");
    }
    
    // Calcul des stats mat2a (rsa transmins, rsa tratés...) concernant l'import
    stats_mat2a($import_id);
    
    
    // Màj de NOWCLOTURE.
    $sqlcmd = "
        SELECT pmsi.cti_now('NOW','FORCE');
        SELECT pmsi.cti_now('NOWCLOTURE','FORCE')";
    $toResult = execute_sql($sqlcmd);
    commit_trans();
    $toResult = execute_sql($sqlcmd);
    commit_trans();
    
    
    logInfoMsg("FIN TRAITEMENTS FINAUX. $nbE erreurs.");
    

}



function generation_validation() {

    global $import_id;

    logInfoMsg("VALIDATION GENERATION");
    
    
    begin_trans();
    
    $nbE = 0;
    
    
    logInfoMsg("Suppression dossiers précédents");
    
    // Les dossiers en-cours non expédiés ne doivent pas être supprimés
    $sqlcmd = "UPDATE pmsi.p_rss set etat = '' WHERE etat = 'S' AND en_cours = '1' AND no_rss NOT IN (SELECT no_rss FROM pmsi.p_rss WHERE import_id = $import_id); ";
     execute_sql($sqlcmd, $nbE, $nbW );

    $sqlcmd = <<<SQL
        CREATE TEMP TABLE temp_rss_to_delete AS
    SELECT oid FROM pmsi.p_rss WHERE etat = 'S';
SQL;
    execute_sql($sqlcmd, $nbE, $nbW );

    $tablesWithRssId = array(
        'p_identites',
        'p_rss_rum',
        'p_rss_diagnostics',
        'p_rss_actes',
        'p_rss_lpp',
        'p_rss_leg',
        'p_rss_maternite',
        'p_rss_ucd',
        'p_rss_transferts',
        'p_rsf_total',
        'p_rsf_detail',
        'p_rsf_detail_non_valorise',
        'p_rsa',
        'p_vidhosp',
        'p_vidhosp_crc',
        'p_vidhosp_dmt',
        'p_vidhosp_dmt_crc',


    );

    foreach ($tablesWithRssId as $table) {
        $sqlcmd = <<<SQL
        DELETE FROM pmsi.$table WHERE rss_id IN (SELECT oid FROM temp_rss_to_delete);
SQL;
        execute_sql($sqlcmd, $nbE, $nbW);
    }

    
    $sqlcmd = "DELETE FROM pmsi.p_rss WHERE p_rss.etat = 'S' AND ghm_id = 0; ";
    execute_sql($sqlcmd, $nbE, $nbW );
    
    // suppression des dossiers réimportés
    $sqlcmd = "DELETE FROM pmsi.p_rss WHERE p_rss.etat = 'S' AND no_rss IN (SELECT no_rss FROM pmsi.p_rss WHERE import_id = $import_id); ";
    execute_sql($sqlcmd, $nbE, $nbW );
    
    
    
    // Chiffrier
    logInfoMsg("Chiffrier mensuel");
    $sqlcmd = "TRUNCATE pmsi.p_chiffrier";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    $sqlcmd = "INSERT INTO pmsi.p_chiffrier (finess, mois, nb_rsa, ca_sejour, nb_rsa_champ_ghs, ca_sejour_champ_ghs, nb_rsa_hors_champ_ghs, ca_sejour_hors_champ_ghs, 
            nb_rsa_en_cours_valides_champ_ghs, nb_rsa_en_cours_groupes_champ_ghs, nb_rsa_en_cours_sortis_non_groupes_champ_ghs, nb_rsa_en_cours_presents_champ_ghs, 
            ca_sejour_en_cours_valides_champ_ghs, ca_sejour_en_cours_groupes_champ_ghs, ca_sejour_en_cours_sortis_non_groupes_champ_ghs, ca_sejour_en_cours_presents_champ_ghs) 
            SELECT 
            p_rss.finess,  
            CASE  
            WHEN p_rss.en_cours <> '1' THEN p_rss.mois_sortie 
            WHEN p_rss.en_cours_etat <> 'P' THEN p_rss.mois_sortie      
            WHEN p_rss.mois_sortie <> 209912 THEN p_rss.mois_sortie  
            ELSE date_part('year',now()) * 100 + date_part('month',now())  
            END AS mois_sortie, 
            sum(p_rss.nb_rsa),  
            sum(p_rsf_total.base_remboursement),  
            SUM(CASE WHEN t_ghm.mco IN ('M', 'C', 'O') AND p_rss.en_cours <> '1' THEN p_rss.nb_rsa ELSE 0 END),  
            SUM(CASE WHEN t_ghm.mco IN ('M', 'C', 'O') AND p_rss.en_cours <> '1' THEN p_rsf_total.base_remboursement ELSE 0 END),  
            SUM(CASE WHEN t_ghm.mco NOT IN ('M', 'C', 'O') AND p_rss.en_cours <> '1' THEN p_rss.nb_rsa ELSE 0 END),  
            SUM(CASE WHEN t_ghm.mco NOT IN ('M', 'C', 'O') AND p_rss.en_cours <> '1' THEN p_rsf_total.base_remboursement ELSE 0 END) , 
            SUM(CASE WHEN t_ghm.mco IN ('M', 'C', 'O') AND p_rss.en_cours LIKE '1' AND p_rss.en_cours_etat IN ('V','F') THEN p_rss.nb_rsa ELSE 0 END), 
            SUM(CASE WHEN t_ghm.mco IN ('M', 'C', 'O') AND p_rss.en_cours LIKE '1' AND p_rss.en_cours_etat = 'G' THEN p_rss.nb_rsa ELSE 0 END), 
            SUM(CASE WHEN p_rss.en_cours LIKE '1' AND p_rss.en_cours_etat = 'S' THEN p_rss.nb_rsa ELSE 0 END), 
            SUM(CASE WHEN p_rss.en_cours LIKE '1' AND p_rss.en_cours_etat = 'P' THEN p_rss.nb_rsa ELSE 0 END), 
            SUM(CASE WHEN t_ghm.mco IN ('M', 'C', 'O') AND p_rss.en_cours LIKE '1' AND p_rss.en_cours_etat IN ('V','F') THEN p_rsf_total.base_remboursement ELSE 0 END), 
            SUM(CASE WHEN t_ghm.mco IN ('M', 'C', 'O') AND p_rss.en_cours LIKE '1' AND p_rss.en_cours_etat = 'G' THEN p_rsf_total.base_remboursement ELSE 0 END), 
            SUM(CASE WHEN p_rss.en_cours LIKE '1' AND p_rss.en_cours_etat = 'S' THEN p_rsf_total.base_remboursement ELSE 0 END), 
            SUM(CASE WHEN p_rss.en_cours LIKE '1' AND p_rss.en_cours_etat = 'P' THEN p_rsf_total.base_remboursement ELSE 0 END) 
            FROM pmsi.p_rss, pmsi.p_rsf_total, pmsi.t_ghm  
            WHERE p_rss.oid = p_rsf_total.rss_id  
            AND ghm_id = t_ghm.oid AND etat = ''  
            AND (en_cours <> '1' OR en_cours_etat IN ('S', 'G', 'V', 'F'))  
            GROUP BY 1, 2";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    $sqlcmd = "UPDATE pmsi.p_imports SET ";
    $sqlcmd = $sqlcmd . "etat_en_cours = '' ";
    $sqlcmd = $sqlcmd . "WHERE oid = $import_id ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );

    $sqlcmd = "UPDATE pmsi.p_imports SET ";
    $sqlcmd = $sqlcmd . "etat = 'G' ";
    $sqlcmd = $sqlcmd . "WHERE oid = $import_id ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    
    commit_trans();
	
	// Chiffrier
    logInfoMsg("Ajustement OVALIDE");
		
	$sqlcmd = "UPDATE pmsi.p_imports
					SET mat2a_import_id = p_mat2a_import.oid
					FROM (
					SELECT p_mat2a_import.mat2a_annee, p_mat2a_import.mat2a_mois, MAX(p_mat2a_import.oid) AS oid
					FROM pmsi.p_mat2a_import
					GROUP BY 1,2
					) p_mat2a_import
					WHERE p_imports.oid = $import_id AND
						date_part('year',p_imports.date_fin) = p_mat2a_import.mat2a_annee AND
						date_part('month',p_imports.date_fin) = p_mat2a_import.mat2a_mois AND
						etat = 'G' AND
						p_imports.oid IN (SELECT import_id FROM pmsi.p_rss WHERE etat = '') AND
						mat2a_import_id IS DISTINCT FROM p_mat2a_import.oid;";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
						
						
    $sqlcmd = "SELECT pmsi.cti_ajust_with_mat2a(-1,mat2a_import_id)
				FROM pmsi.p_imports
				WHERE oid = $import_id AND mat2a_import_id <> 0 AND
					oid IN
					(
						SELECT import_id
						FROM
						(
							SELECT
							annee_rss, (MAX(ARRAY[nb,import_id]))[2] AS import_id
							FROM
							(
								SELECT 
								date_part('year',date_sortie) AS annee_rss, import_id, count(*) AS nb
								FROM pmsi.p_rss
								WHERE import_id > 0 AND
								date_sortie >= '20180101' AND
								etat = ''
								GROUP BY 1,2
							) subview
							GROUP BY 1
						) subview
					)
				";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    logInfoMsg("FIN VALIDATION GENERATION. $nbE erreurs.");
    
}

function set_oids() {

    global $ENDSTATUS;
    global $iCTI_connexion;

    logInfoMsg("REFERENCEMENT PARAMETRES");
    
    $nb = 0;
    $nbW = 0;
    $nbE = 0;
    
    begin_trans();

    
    

    
    // RAZ
    $sqlcmd = "TRUNCATE pmsi.p_oids ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();

    // FINESS
    $sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) 
				SELECT 'finess', t_finess.oid FROM pmsi.p_rss JOIN base.t_finess ON p_rss.finess = t_finess.code GROUP BY 1,2; ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    // medecins rss
    $sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'medecins_rss', medecin_rss_id FROM pmsi.p_rss WHERE medecin_rss_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'medecins_rss')";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();

    // medecins actes
    $sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'medecins_acte', medecin_id FROM pmsi.p_rss_actes WHERE medecin_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'medecins_acte')";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();

    // medecins interventions
    $sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'medecins_intervention', medecin_id FROM pmsi.v_rss_actes_1 WHERE acte_regroupement_code IN ('ADC', 'ADO') AND medecin_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'medecins_intervention')";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    // anesthésistes interventions
    $sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'anesthesistes_intervention', medecin_id FROM pmsi.v_rss_actes_1 WHERE acte_regroupement_code = 'ADA' AND medecin_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'anesthesistes_intervention')";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();

    // medecins rum
    $sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'medecins_rum', medecin_rum_id FROM pmsi.p_rss_rum WHERE medecin_rum_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'medecins_rum')";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    //diagnostics
    $sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'diagnostics', diagnostic_id FROM pmsi.p_rss_diagnostics WHERE diagnostic_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'diagnostics'); ";
    $sqlcmd = $sqlcmd . "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'diagnostics', diagnostic_principal_id FROM pmsi.p_rss WHERE diagnostic_principal_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'diagnostics') ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
        
    // actes
    $sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'actes', acte_id FROM pmsi.p_rss_actes WHERE acte_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'actes')";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
	
	$sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'actes', acte_ccam_descriptif_id FROM pmsi.p_rss_actes WHERE acte_ccam_descriptif_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'actes')";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    $sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'actes', acte_id FROM pmsi.p_rsf_detail_h WHERE acte_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'actes')";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    // ghm
    $sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'ghm', ghm_id FROM pmsi.p_rss WHERE ghm_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'ghm')";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();

    // prestations
    $sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'prestations', prestation_id FROM pmsi.p_rsf_detail WHERE p_rsf_detail.est_ligne_rss = '1' AND prestation_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'prestations')";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    $sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'prestations', prestation_id FROM pmsi.p_rsf_detail_non_valorise WHERE prestation_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'prestations')";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();

    // prestations
    $sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'prestations_p', prestation_principale_id FROM pmsi.p_rss WHERE prestation_principale_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'prestations_p')";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();

    // prestations honoraires
    $sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'prestations_h', prestation_id FROM pmsi.p_rsf_detail WHERE p_rsf_detail.type = 'C' AND p_rsf_detail.est_ligne_rss = '1' AND prestation_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'prestations_h')";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    // lpp
    $sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'lpp', lpp_id FROM pmsi.p_rss_lpp WHERE lpp_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'lpp')";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    // ucd
    $sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'ucd', ucd_id FROM pmsi.p_rss_ucd WHERE ucd_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'ucd')";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();    
    
    // indication ucd
    $sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'INDICATIONUCD', indication_id FROM pmsi.p_rss_ucd WHERE indication_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'INDICATIONUCD')";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();

    // ghs
    $sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'ghs', ghs_id FROM pmsi.p_rsf_detail WHERE ghs_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'ghs')";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();

    // departements
    $sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'departement', t_departements.oid FROM base.t_departements, base.t_codes_postaux ";
    $sqlcmd = $sqlcmd . "WHERE t_codes_postaux.departement_id = t_departements.oid  ";
    $sqlcmd = $sqlcmd . "AND t_codes_postaux.oid in (SELECT DISTINCT code_postal_id FROM pmsi.p_rss) ";
    $sqlcmd = $sqlcmd . "AND t_departements.oid NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'departement')";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    // codes postaux
    $sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'c_postaux', oid FROM base.t_codes_postaux WHERE code in (SELECT DISTINCT code_postal FROM pmsi.p_rss) AND oid NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'c_postaux')";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();

    // um
    $sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'um', unite_medicale_id FROM pmsi.p_rss_rum WHERE unite_medicale_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'um')";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();

    // uf
    $sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'uf', unite_fonctionnelle_id FROM pmsi.p_rss_actes WHERE unite_fonctionnelle_id != ALL (ARRAY(SELECT oid FROM pmsi.p_oids WHERE code_table = 'uf')::bigint[])";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
	
    // durées de séjour
    $sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'dursej', duree_sejour FROM pmsi.p_rss WHERE duree_sejour NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'dursej')";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();

    
    analyse_table("p_oids");
    
    $sqlcmd = "SELECT pmsi.cti_reorganize_medecins_c() ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();

    $sqlcmd = "VACUUM FULL pmsi.t_medecins_c; ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();

    
    $sqlcmd = "SELECT pmsi.cti_reorganize_ghm_c() ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();

    $sqlcmd = "VACUUM FULL pmsi.t_ghm_c; ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();

    
    $sqlcmd = "SELECT pmsi.cti_reorganize_actes_c() ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    

    $sqlcmd = "VACUUM FULL pmsi.t_actes_c; ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    $sqlcmd = "SELECT pmsi.cti_reorganize_durees_sejour_c() ";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();

    
    $sqlcmd = "SELECT pmsi.cti_update_schema_classes('*ALL')";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW );
    commit_trans();
    
    // Suppression des pb d'intégrités éventuels avec RSS
    $sqlcmd = "SELECT pmsi.cti_verify_rss_tables()";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
    commit_trans();
    
    
    logInfoMsg("FIN REFERENCEMENT PARAMETRES. $nbE erreurs.");

}

function read_med_line($buffer) {

    $BUF_record = array();
    $buffer = Encoding::removeBOM($buffer);

    $buffer = str_ireplace(";", "\t", $buffer);
    $array = split("\t", $buffer);

    
    

    $BUF_record["code"] = trim(substr(trim($array[0]),0,8));
    $BUF_record["code_offset"] = 0;
    $BUF_record["code_len"] = strlen($array[0]);
    $BUF_record["nom"] = trim($array[1]);
    $BUF_record["nom_offset"] = $BUF_record["code_offset"] + $BUF_record["code_len"] + 1;
    $BUF_record["nom_len"] = strlen($array[1]);
    $BUF_record["prenom"] = trim($array[2]);
    $BUF_record["prenom_offset"] = $BUF_record["nom_offset"] + $BUF_record["nom_len"] + 1;
    $BUF_record["prenom_len"] = strlen($array[2]);
    $BUF_record["specialite"] = trim($array[3]);
    $BUF_record["specialite_offset"] = $BUF_record["prenom_offset"] + $BUF_record["prenom_len"] + 1;
    $BUF_record["specialite_len"] = strlen($array[3]);
    $BUF_record["no_adeli"] = trim($array[4]);
    $BUF_record["no_adeli_offset"] = $BUF_record["specialite_offset"] + $BUF_record["specialite_len"] + 1;
    $BUF_record["no_adeli_len"] = strlen($array[4]);
    
    
        
    
    return $BUF_record;
        

}

function read_rssmed_line($buffer) {

    $BUF_record = array();
    $buffer = Encoding::removeBOM($buffer);

    $buffer = str_ireplace(";", "\t", $buffer);
    $array = split("\t", $buffer);


    $BUF_record["no_rss"] = trim($array[0]);
    $BUF_record["no_rss_offset"] = 0;
    $BUF_record["no_rss_len"] = strlen($array[0]);
    $BUF_record["code_medecin"] = trim(substr(trim($array[1]),0,8));
    $BUF_record["code_medecin_offset"] = $BUF_record["no_rss_offset"] + $BUF_record["no_rss_len"] + 1;
    $BUF_record["code_medecin_len"] = strlen($array[1]);
    $BUF_record["is_comite"] = '0';
    if (@trim($array[2]) == "*CMM") {
        $BUF_record["is_comite"] = '1';
    }
        
    return $BUF_record;
        
}

function read_rssnom_line($buffer) {

    $BUF_record = array();
    $buffer = Encoding::removeBOM($buffer);

    $buffer = str_ireplace(";", "\t", $buffer);
    $array = split("\t", $buffer);

    $BUF_record["no_rss"] = trim($array[0]);
    $BUF_record["no_rss_offset"] = 0;
    $BUF_record["no_rss_len"] = strlen($array[0]);
    $BUF_record["nom"] = strtoupper(trim($array[1]));
    $BUF_record["nom_offset"] = $BUF_record["no_rss_offset"] + $BUF_record["no_rss_len"] + 1;
    $BUF_record["nom_len"] = strlen($array[1]);
    $BUF_record["prenom"] = strtoupper(trim($array[2]));
    $BUF_record["prenom_offset"] = $BUF_record["nom_offset"] + $BUF_record["nom_len"] + 1;
    $BUF_record["prenom_len"] = strlen($array[2]);
    $BUF_record["no_patient"] = 0;
    $BUF_record["no_patient_offset"] = 0;
    $BUF_record["no_patient_len"] = 0;
    if (count($array) > 3) {
        $BUF_record["no_patient"] = $array[3] + 0;
        $BUF_record["no_patient_offset"] = $BUF_record["prenom_offset"] + $BUF_record["prenom_len"] + 1;
        $BUF_record["no_patient_len"] = strlen($array[3]);
    }
    
    return $BUF_record;
        
}


function read_actmed_line($buffer) {

    global $fmt_actemed;

    $BUF_record = array();
    $buffer = Encoding::removeBOM($buffer);

    $BUF_record["type_enregistrement"] = "";
    
    $buffer = str_ireplace(";", "\t", $buffer);
    $array = split("\t", $buffer);
    
    if ($fmt_actemed != 1 && $fmt_actemed != 2) {
        $fmt_actemed = 1;
        if (count($array) < 10) {
            $fmt_actemed = 1;
        }
        else {
            if (controle_check_date(trim($array[6]),$fil1,$fil2)) {
                $fmt_actemed = 1;
            }
            else {
                $fmt_actemed = 2;
            }
        }
    }
    
    

    // Standard
    if ($fmt_actemed == 1) {
        $BUF_record["no_rss"] = trim($array[0]);
        $BUF_record["no_rss_offset"] = 0;
        $BUF_record["no_rss_len"] = strlen($array[0]);
        $BUF_record["code_medecin"] = trim(substr(trim($array[1]),0,8));
        $BUF_record["code_medecin_offset"] = $BUF_record["no_rss_offset"] + $BUF_record["no_rss_len"] + 1;
        $BUF_record["code_medecin_len"] = strlen($array[1]);
        $BUF_record["code_acte"] = trim($array[2]);
        $BUF_record["code_acte_offset"] = $BUF_record["code_medecin_offset"] + $BUF_record["code_medecin_len"]+ 1;
        $BUF_record["code_acte_len"] = strlen($array[2]);
        $BUF_record["activite_ccam"] = trim($array[3]);
        $BUF_record["activite_ccam_offset"] = $BUF_record["code_acte_offset"] + $BUF_record["code_acte_len"]+ 1;
        $BUF_record["activite_ccam_len"] = strlen($array[3]);
        $BUF_record["phase_ccam"] = trim($array[4]);
        $BUF_record["phase_ccam_offset"] = $BUF_record["activite_ccam_offset"] + $BUF_record["activite_ccam_len"]+ 1;
        $BUF_record["phase_ccamlen"] = strlen($array[4]);
        $BUF_record["unite_medicale"] = trim($array[5]);
        $BUF_record["unite_medicale_offset"] = $BUF_record["phase_ccam_offset"] + $BUF_record["phase_ccam_len"]+ 1;
        $BUF_record["unite_medicale_len"] = strlen($array[5]);
        $BUF_record["date_acte"] = trim($array[6]);
        $BUF_record["date_acte_offset"] = $BUF_record["unite_medicale_offset"] + $BUF_record["unite_medicale_len"]+ 1;
        $BUF_record["date_acte_len"] = strlen($array[6]);
        $BUF_record["nombre"] = trim($array[7]);
        $BUF_record["nombre_offset"] = $BUF_record["date_acte_offset"] + $BUF_record["date_acte_len"]+ 1;
        $BUF_record["nombre_len"] = strlen($array[7]);
        $BUF_record["no_rum"] = trim($array[8]);
        $BUF_record["no_rum_offset"] = $BUF_record["nombre_offset"] + $BUF_record["nombre_len"]+ 1;
        $BUF_record["no_rum_len"] = strlen($array[8]);
    }
    // CEGI
    else {
        $BUF_record["no_rss"] = trim($array[0]);
        $BUF_record["no_rss_offset"] = 0;
        $BUF_record["no_rss_len"] = strlen($array[0]);
        $BUF_record["code_medecin"] = trim(substr(trim($array[1]),0,8));
        $BUF_record["code_medecin_offset"] = $BUF_record["no_rss_offset"] + $BUF_record["no_rss_len"]+ 1;
        $BUF_record["code_medecin_len"] = strlen($array[1]);
        $BUF_record["code_acte"] = trim($array[2]);
        $BUF_record["code_acte_offset"] = $BUF_record["code_medecin_offset"] + $BUF_record["code_medecin_len"]+ 1;
        $BUF_record["code_acte_len"] = strlen($array[2]);
        $BUF_record["activite_ccam"] = trim($array[3]);
        $BUF_record["activite_ccam_offset"] = $BUF_record["code_acte_offset"] + $BUF_record["code_acte_len"]+ 1;
        $BUF_record["activite_ccam_len"] = strlen($array[3]);
        $BUF_record["phase_ccam"] = trim($array[4]);
        $BUF_record["phase_ccam_offset"] = $BUF_record["activite_ccam_offset"] + $BUF_record["activite_ccam_len"]+ 1;
        $BUF_record["phase_ccamlen"] = strlen($array[4]);
        $BUF_record["date_acte"] = trim($array[5]);
        $BUF_record["date_acte_offset"] = $BUF_record["phase_ccam_offset"] + $BUF_record["phase_ccam_len"]+ 1;
        $BUF_record["date_acte_len"] = strlen($array[5]);
        $BUF_record["heure_acte"] = trim($array[5]);
        $BUF_record["heure_acte_offset"] = $BUF_record["date_acte_offset"] + $BUF_record["date_acte_len"]+ 1;
        $BUF_record["heure_acte_len"] = strlen($array[6]);
        $BUF_record["modif1"] = trim($array[7]);
        $BUF_record["modif1_offset"] = $BUF_record["heure_acte_offset"] + $BUF_record["heure_acte_len"]+ 1;
        $BUF_record["modif1_len"] = strlen($array[7]);
        $BUF_record["modif2"] = trim($array[8]);
        $BUF_record["modif2_offset"] = $BUF_record["modif1_offset"] + $BUF_record["modif1_len"]+ 1;
        $BUF_record["modif2_len"] = strlen($array[8]);
        $BUF_record["modif3"] = trim($array[9]);
        $BUF_record["modif3_offset"] = $BUF_record["modif2_offset"] + $BUF_record["modif2_len"]+ 1;
        $BUF_record["modif3_len"] = strlen($array[9]);
        $BUF_record["modif4"] = trim($array[10]);
        $BUF_record["modif4_offset"] = $BUF_record["modif3_offset"] + $BUF_record["modif3_len"]+ 1;
        $BUF_record["modif4_len"] = strlen($array[10]);
        $BUF_record["ass"] = trim($array[11]);
        $BUF_record["ass_offset"] = $BUF_record["modif4_offset"] + $BUF_record["modif4_len"]+ 1;
        $BUF_record["ass_len"] = strlen($array[11]);
        $BUF_record["remb"] = trim($array[12]);
        $BUF_record["remb_offset"] = $BUF_record["ass_offset"] + $BUF_record["ass_len"]+ 1;
        $BUF_record["remb_len"] = strlen($array[12]);
    }
    
    if ($BUF_record["code_medecin"] != "") {
        $BUF_record["type_enregistrement"] = "ACTMED";
    }
        
    return $BUF_record;

}


function read_rum_line($buffer, $qAD = TRUE) {

    global $last_BUF_rss;
    global $last_BUF_rum;
    
    global $rss_offsets_122;
	global $rss_offsets_121;
	global $rss_offsets_120;
    global $rss_offsets_119;
    global $rss_offsets_117;
    global $rss_offsets_114;
    global $rss_offsets_113;
    global $rss_offsets_111;
    global $rss_offsets_110;
    global $rss_offsets_109;

    $BUF_record = array();
    $buffer = Encoding::removeBOM($buffer);

    if (is_entete_empty($buffer)){
        $BUF_record["type_enregistrement"] = "ENTETE";
        return $BUF_record;
    }

    if (trim(substr($buffer, 27, 5) == "NRSS0")) {
        $BUF_record["type_enregistrement"] = "NONE";
        return $BUF_record;
    }
    
    $BUF_record["type_enregistrement"] = "RUM";
    

    $BUF_record["actes"] = array();
    $BUF_record["diags"] = array();
    $BUF_record["diagsdoc"] = array();

    $BUF_record["version_groupage"] = trim(substr($buffer, 0, 2));
    $BUF_record["ghm"] = trim(substr($buffer, 2, 6));
    $BUF_record["version_format"] = trim(substr($buffer, 9, 3));
    $BUF_record["groupage_retour"] = trim(substr($buffer, 12, 3));
    $BUF_record["finess"] = trim(substr($buffer, 15, 9));
    $BUF_record["version_format_rum"] = trim(substr($buffer, 24, 3));
    $BUF_record["no_rss"] = "";
    
    $BUF_record["fmt_error"] = "";
    
    
    
    // Correction si pb 114 avec actes longueur 2
    if ($BUF_record["version_format"] == "114") {
        $char = trim(substr($buffer, 131, 1));
        if ($char >= "A" && $char <= "Z" && $char != "") {
            $BUF_record["version_format"] = "113";
            $BUF_record["fmt_error"] = "Format 114 indiqué mais formaté comme le format 113";
        }
    }
    
    // Initialisation des champs
    $BUF_record["age_gestationnel"] = "";
    $BUF_record["annee_ivg_precedente"] = "0000";
    $BUF_record["code_postal"] = "";
    $BUF_record["confirmation_codage"] = "";
    $BUF_record["date_dernieres_regles"] = "";
    $BUF_record["date_entree"] = "";
    $BUF_record["date_naissance"] = "";
    $BUF_record["date_sortie"]= "";
    $BUF_record["destination"] = "";
    $BUF_record["diagnostic_principal"] = "";
    $BUF_record["diagnostic_relie"] = "";
    $BUF_record["igs2"] = "000";
    $BUF_record["mode_entree"] = "";
    $BUF_record["mode_sortie"] = "";
    $BUF_record["passage_urgences"] = "";
    $BUF_record["no_rss"] = "";
    $BUF_record["no_rum"] = "";
    $BUF_record["no_sejour_administratif"] = "";
    $BUF_record["nombre_actes"] = "00";
    $BUF_record["nombre_diagnostics"] = "";
    $BUF_record["nombre_donnees_documentaires"] = "";
    $BUF_record["nombre_ivg_anterieures"] = "00";
    $BUF_record["nombre_naissances_vivantes_anterieures"] = "00";
    $BUF_record["nombre_seances"] = "";
    $BUF_record["numero_innovation"] = "";
    $BUF_record["poids_bebe"] = "";
    $BUF_record["provenance"] = "";
    $BUF_record["sexe"] = "";
    $BUF_record["type_autorisation_lit"] = "";
    $BUF_record["type_autorisation_um"] = "";
    $BUF_record["type_dosimetrie"] = "";
    $BUF_record["type_machine_rdth"] = "";
    $BUF_record["unite_medicale"] = "";
    $BUF_record["filler"] = "";
    $BUF_record["conversion_hp_hc"] = "";   // 1:conversion HP-HC | 2:pas de conversion | blanc
    $BUF_record["raac"] = "";   // 1:prise en charge RAAC | 2:pas de prise en charge | blanc
        
    switch ($BUF_record["version_format"]) {
    // Format 109 CDAM paas d'acte
    case "109" :
        $BUF_record["BUF_offsets"] = $rss_offsets_109;
        $BUF_record["no_rss"] = trim(substr($buffer, 27, 7));
        $BUF_record["no_sejour_administratif"] = "";
        if ($last_BUF_rss !== $BUF_record["no_rss"]) {
            $last_BUF_rum = 0;
            $last_BUF_rss = $BUF_record["no_rss"];
        }
        $last_BUF_rum++;
        $BUF_record["no_rum"] = $last_BUF_rum;
        $BUF_record["date_naissance"] = trim(substr($buffer, 34, 8));
        $BUF_record["sexe"] = trim(substr($buffer, 42, 1));
        $BUF_record["unite_medicale"] = trim(substr($buffer, 43, 4));
        $BUF_record["date_entree"] = trim(substr($buffer, 47, 8));
        $BUF_record["mode_entree"] = trim(substr($buffer, 55, 1));
        $BUF_record["provenance"] = trim(substr($buffer, 56, 1));
        $BUF_record["date_sortie"] = trim(substr($buffer, 57, 8));
        $BUF_record["mode_sortie"] = trim(substr($buffer, 65, 1));
        $BUF_record["destination"] = trim(substr($buffer, 66, 1));
        $BUF_record["code_postal"] = substr($buffer, 67, 5);
        $BUF_record["poids_bebe"] = trim(substr($buffer, 72, 4));
        $BUF_record["nombre_seances"] = trim(substr($buffer, 76, 2));
        $BUF_record["nombre_diagnostics"] = trim(substr($buffer, 78, 2));
        $BUF_record["nombre_donnees_documentaires"] = trim(substr($buffer, 80, 2));
        $BUF_record["diagnostic_principal"] = trim(substr($buffer, 84, 8));
        $BUF_record["diagnostic_relie"] = trim(substr($buffer, 92, 8));
        $BUF_record["igs2"] = trim(substr($buffer, 100, 3));
        $BUF_start = 118;
        break;
    case "110" :
        $BUF_record["BUF_offsets"] = $rss_offsets_110;
        $BUF_record["no_rss"] = trim(substr($buffer, 27, 7));
        $BUF_record["no_sejour_administratif"] = "";
        if ($last_BUF_rss !== $BUF_record["no_rss"]) {
            $last_BUF_rum = 0;
            $last_BUF_rss = $BUF_record["no_rss"];
        }
        $last_BUF_rum++;
        $BUF_record["no_rum"] = $last_BUF_rum;
        $BUF_record["date_naissance"] = trim(substr($buffer, 34, 8));
        $BUF_record["sexe"] = trim(substr($buffer, 42, 1));
        $BUF_record["unite_medicale"] = trim(substr($buffer, 43, 4));
        $BUF_record["date_entree"] = trim(substr($buffer, 47, 8));
        $BUF_record["mode_entree"] = trim(substr($buffer, 55, 1));
        $BUF_record["provenance"] = trim(substr($buffer, 56, 1));
        $BUF_record["date_sortie"] = trim(substr($buffer, 57, 8));
        $BUF_record["mode_sortie"] = trim(substr($buffer, 65, 1));
        $BUF_record["destination"] = trim(substr($buffer, 66, 1));
        $BUF_record["code_postal"] = substr($buffer, 67, 5);
        $BUF_record["poids_bebe"] = trim(substr($buffer, 72, 4));
        $BUF_record["nombre_seances"] = trim(substr($buffer, 76, 2));
        $BUF_record["nombre_diagnostics"] = trim(substr($buffer, 78, 2));
        $BUF_record["nombre_donnees_documentaires"] = trim(substr($buffer, 80, 2));
        $BUF_record["nombre_actes"] = trim(substr($buffer, 82, 2));
        $BUF_record["diagnostic_principal"] = trim(substr($buffer, 84, 8));
        $BUF_record["diagnostic_relie"] = trim(substr($buffer, 92, 8));
        $BUF_record["igs2"] = trim(substr($buffer, 100, 3));
        $BUF_start = 118;
        break;
    case "111" :
        $BUF_record["BUF_offsets"] = $rss_offsets_111;
        $BUF_record["no_rss"] = trim(substr($buffer, 27, 7));
        $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 34, 20));
        if ($last_BUF_rss !== $BUF_record["no_rss"]) {
            $last_BUF_rum = 0;
            $last_BUF_rss = $BUF_record["no_rss"];
        }
        $last_BUF_rum++;
        $BUF_record["no_rum"] = $last_BUF_rum;
        $BUF_record["date_naissance"] = trim(substr($buffer, 54, 8));
        $BUF_record["sexe"] = trim(substr($buffer, 62, 1));
        $BUF_record["unite_medicale"] = trim(substr($buffer, 63, 4));
        $BUF_record["type_autorisation_um"] = trim(substr($buffer, 67, 2));
        $BUF_record["type_autorisation_lit"] = trim(substr($buffer, 69, 2));
        $BUF_record["date_entree"] = trim(substr($buffer, 72, 8));
        $BUF_record["mode_entree"] = trim(substr($buffer, 80, 1));
        $BUF_record["provenance"] = trim(substr($buffer, 81, 1));
        $BUF_record["date_sortie"] = trim(substr($buffer, 82, 8));
        $BUF_record["mode_sortie"] = trim(substr($buffer, 90, 1));
        $BUF_record["destination"] = trim(substr($buffer, 91, 1));
        $BUF_record["code_postal"] = substr($buffer, 92, 5);
        $BUF_record["poids_bebe"] = trim(substr($buffer, 97, 4));
        $BUF_record["nombre_seances"] = trim(substr($buffer, 101, 2));
        $BUF_record["nombre_diagnostics"] = trim(substr($buffer, 103, 2));
        $BUF_record["nombre_donnees_documentaires"] = trim(substr($buffer, 105, 2));
        $BUF_record["nombre_actes"] = trim(substr($buffer, 107, 2));
        $BUF_record["diagnostic_principal"] = trim(substr($buffer, 109, 8));
        $BUF_record["diagnostic_relie"] = trim(substr($buffer, 117, 8));
        $BUF_record["igs2"] = trim(substr($buffer, 125, 3));
        $BUF_start = 143;
        break;
    case "113" :
        $BUF_record["BUF_offsets"] = $rss_offsets_113;
        $BUF_record["no_rss"] = trim(substr($buffer, 27, 20));
        $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 47, 20));
        $BUF_record["no_rum"] = trim(substr($buffer, 67, 10));
        if ($last_BUF_rss !== $BUF_record["no_rss"]) {
            $last_BUF_rum = 0;
            $last_BUF_rss = $BUF_record["no_rss"];
        }
        $last_BUF_rum++;
        $BUF_record["no_rum"] = $last_BUF_rum;
        $BUF_record["date_naissance"] = trim(substr($buffer, 77, 8));
        $BUF_record["sexe"] = trim(substr($buffer, 85, 1));
        $BUF_record["unite_medicale"] = trim(substr($buffer, 86, 4));
        $BUF_record["type_autorisation_lit"] = trim(substr($buffer, 90, 2));
        $BUF_record["date_entree"] = trim(substr($buffer, 92, 8));
        $BUF_record["mode_entree"] = trim(substr($buffer, 100, 1));
        $BUF_record["provenance"] = trim(substr($buffer, 101, 1));
        $BUF_record["date_sortie"]= trim(substr($buffer, 102, 8));
        $BUF_record["mode_sortie"] = trim(substr($buffer, 110, 1));
        $BUF_record["destination"] = trim(substr($buffer, 111, 1));
        $BUF_record["code_postal"] = substr($buffer, 112, 5);
        $BUF_record["poids_bebe"] = trim(substr($buffer, 117, 4));
        $BUF_record["age_gestationnel"] = trim(substr($buffer, 121, 2));
        $BUF_record["nombre_seances"] = trim(substr($buffer, 123, 2));
        $BUF_record["nombre_diagnostics"] = trim(substr($buffer, 125, 2));
        $BUF_record["nombre_donnees_documentaires"] = trim(substr($buffer, 127, 2));
        $BUF_record["nombre_actes"] = trim(substr($buffer, 129, 2));
        $BUF_record["diagnostic_principal"] = trim(substr($buffer, 131, 8));
        $BUF_record["diagnostic_relie"] = trim(substr($buffer, 139, 8));
        $BUF_record["igs2"] = trim(substr($buffer, 147, 3));
        $BUF_start = 165;
        break;
    
    case "114" :
        $BUF_record["BUF_offsets"] = $rss_offsets_114;
        $BUF_record["no_rss"] = trim(substr($buffer, 27, 20));
        $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 47, 20));
        $BUF_record["no_rum"] = trim(substr($buffer, 67, 10));
        if ($last_BUF_rss !== $BUF_record["no_rss"]) {
            $last_BUF_rum = 0;
            $last_BUF_rss = $BUF_record["no_rss"];
        }
        $last_BUF_rum++;
        $BUF_record["no_rum"] = $last_BUF_rum;
        $BUF_record["date_naissance"] = trim(substr($buffer, 77, 8));
        $BUF_record["sexe"] = trim(substr($buffer, 85, 1));
        $BUF_record["unite_medicale"] = trim(substr($buffer, 86, 4));
        $BUF_record["type_autorisation_lit"] = trim(substr($buffer, 90, 2));
        $BUF_record["date_entree"] = trim(substr($buffer, 92, 8));
        $BUF_record["mode_entree"] = trim(substr($buffer, 100, 1));
        $BUF_record["provenance"] = trim(substr($buffer, 101, 1));
        $BUF_record["date_sortie"]= trim(substr($buffer, 102, 8));
        $BUF_record["mode_sortie"] = trim(substr($buffer, 110, 1));
        $BUF_record["destination"] = trim(substr($buffer, 111, 1));
        $BUF_record["code_postal"] = substr($buffer, 112, 5);
        $BUF_record["poids_bebe"] = trim(substr($buffer, 117, 4));
        $BUF_record["age_gestationnel"] = trim(substr($buffer, 121, 2));
        $BUF_record["nombre_seances"] = trim(substr($buffer, 123, 2));
        $BUF_record["nombre_diagnostics"] = trim(substr($buffer, 125, 2));
        $BUF_record["nombre_donnees_documentaires"] = trim(substr($buffer, 127, 2));
        $BUF_record["nombre_actes"] = trim(substr($buffer, 129, 3));
        $BUF_record["diagnostic_principal"] = trim(substr($buffer, 132, 8));
        $BUF_record["diagnostic_relie"] = trim(substr($buffer, 140, 8));
        $BUF_record["igs2"] = trim(substr($buffer, 148, 3));
        $BUF_record["confirmation_codage"] = trim(substr($buffer, 151, 1));
        $BUF_record["type_machine_rdth"] = trim(substr($buffer, 152, 1));
        $BUF_record["type_dosimetrie"] = trim(substr($buffer, 153, 1));
        $BUF_start = 165;
        break;
    case "115" :
        $BUF_record["BUF_offsets"] = $rss_offsets_114;
        $BUF_record["no_rss"] = trim(substr($buffer, 27, 20));
        $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 47, 20));
        
        $BUF_record["no_rum"] = trim(substr($buffer, 67, 10));
        if ($last_BUF_rss !== $BUF_record["no_rss"]) {
            $last_BUF_rum = 0;
            $last_BUF_rss = $BUF_record["no_rss"];
        }
        $last_BUF_rum++;
        $BUF_record["no_rum"] = $last_BUF_rum;
        $BUF_record["date_naissance"] = trim(substr($buffer, 77, 8));
        $BUF_record["sexe"] = trim(substr($buffer, 85, 1));
        $BUF_record["unite_medicale"] = trim(substr($buffer, 86, 4));
        $BUF_record["type_autorisation_lit"] = trim(substr($buffer, 90, 2));
        $BUF_record["date_entree"] = trim(substr($buffer, 92, 8));
        $BUF_record["mode_entree"] = trim(substr($buffer, 100, 1));
        $BUF_record["provenance"] = trim(substr($buffer, 101, 1));
        $BUF_record["date_sortie"]= trim(substr($buffer, 102, 8));
        $BUF_record["mode_sortie"] = trim(substr($buffer, 110, 1));
        $BUF_record["destination"] = trim(substr($buffer, 111, 1));
        $BUF_record["code_postal"] = substr($buffer, 112, 5);
        $BUF_record["poids_bebe"] = trim(substr($buffer, 117, 4));
        $BUF_record["age_gestationnel"] = trim(substr($buffer, 121, 2));
        $BUF_record["nombre_seances"] = trim(substr($buffer, 123, 2));
        $BUF_record["nombre_diagnostics"] = trim(substr($buffer, 125, 2));
        $BUF_record["nombre_donnees_documentaires"] = trim(substr($buffer, 127, 2));
        $BUF_record["nombre_actes"] = trim(substr($buffer, 129, 3));
        $BUF_record["diagnostic_principal"] = trim(substr($buffer, 132, 8));
        $BUF_record["diagnostic_relie"] = trim(substr($buffer, 140, 8));
        $BUF_record["igs2"] = trim(substr($buffer, 148, 3));
        $BUF_record["confirmation_codage"] = trim(substr($buffer, 151, 1));
        $BUF_record["type_machine_rdth"] = trim(substr($buffer, 152, 1));
        $BUF_record["type_dosimetrie"] = trim(substr($buffer, 153, 1));
        $BUF_start = 165;
        break;
    
    case "116" :
        $BUF_record["BUF_offsets"] = $rss_offsets_114;
        $BUF_record["no_rss"] = trim(substr($buffer, 27, 20));
        $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 47, 20));
        $BUF_record["no_rum"] = trim(substr($buffer, 67, 10));
        if ($last_BUF_rss !== $BUF_record["no_rss"]) {
            $last_BUF_rum = 0;
            $last_BUF_rss = $BUF_record["no_rss"];
        }
        $last_BUF_rum++;
        $BUF_record["no_rum"] = $last_BUF_rum;
        $BUF_record["date_naissance"] = trim(substr($buffer, 77, 8));
        $BUF_record["sexe"] = trim(substr($buffer, 85, 1));
        $BUF_record["unite_medicale"] = trim(substr($buffer, 86, 4));
        $BUF_record["type_autorisation_lit"] = trim(substr($buffer, 90, 2));
        $BUF_record["date_entree"] = trim(substr($buffer, 92, 8));
        $BUF_record["mode_entree"] = trim(substr($buffer, 100, 1));
        $BUF_record["provenance"] = trim(substr($buffer, 101, 1));
        $BUF_record["date_sortie"]= trim(substr($buffer, 102, 8));
        $BUF_record["mode_sortie"] = trim(substr($buffer, 110, 1));
        $BUF_record["destination"] = trim(substr($buffer, 111, 1));
        $BUF_record["code_postal"] = substr($buffer, 112, 5);
        $BUF_record["poids_bebe"] = trim(substr($buffer, 117, 4));
        $BUF_record["age_gestationnel"] = trim(substr($buffer, 121, 2));
        $BUF_record["date_dernieres_regles"] = trim(substr($buffer, 123, 8));
        $BUF_record["nombre_seances"] = trim(substr($buffer, 131, 2));
        $BUF_record["nombre_diagnostics"] = trim(substr($buffer, 133, 2));
        $BUF_record["nombre_donnees_documentaires"] = trim(substr($buffer, 135, 2));
        $BUF_record["nombre_actes"] = trim(substr($buffer, 137, 3));
        $BUF_record["diagnostic_principal"] = trim(substr($buffer, 140, 8));
        $BUF_record["diagnostic_relie"] = trim(substr($buffer, 148, 8));
        $BUF_record["igs2"] = trim(substr($buffer, 156, 3));
        $BUF_record["confirmation_codage"] = trim(substr($buffer, 159, 1));
        $BUF_record["type_machine_rdth"] = trim(substr($buffer, 160, 1));
        $BUF_record["type_dosimetrie"] = trim(substr($buffer, 161, 1));
        $BUF_record["numero_innovation"] = trim(substr($buffer, 162, 15));
        $BUF_start = 192;
        break;
    case "117" :
        $BUF_record["BUF_offsets"] = $rss_offsets_117;
        $BUF_record["no_rss"] = trim(substr($buffer, 27, 20));
        $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 47, 20));
        $BUF_record["no_rum"] = trim(substr($buffer, 67, 10));
        if ($last_BUF_rss !== $BUF_record["no_rss"]) {
            $last_BUF_rum = 0;
            $last_BUF_rss = $BUF_record["no_rss"];
        }
        $last_BUF_rum++;
        $BUF_record["no_rum"] = $last_BUF_rum;
        $BUF_record["date_naissance"] = trim(substr($buffer, 77, 8));
        $BUF_record["sexe"] = trim(substr($buffer, 85, 1));
        $BUF_record["unite_medicale"] = trim(substr($buffer, 86, 4));
        $BUF_record["type_autorisation_lit"] = trim(substr($buffer, 90, 2));
        $BUF_record["date_entree"] = trim(substr($buffer, 92, 8));
        $BUF_record["mode_entree"] = trim(substr($buffer, 100, 1));
        $BUF_record["provenance"] = trim(substr($buffer, 101, 1));
        $BUF_record["date_sortie"]= trim(substr($buffer, 102, 8));
        $BUF_record["mode_sortie"] = trim(substr($buffer, 110, 1));
        $BUF_record["destination"] = trim(substr($buffer, 111, 1));
        $BUF_record["code_postal"] = substr($buffer, 112, 5);
        $BUF_record["poids_bebe"] = trim(substr($buffer, 117, 4));
        $BUF_record["age_gestationnel"] = trim(substr($buffer, 121, 2));
        $BUF_record["date_dernieres_regles"] = trim(substr($buffer, 123, 8));
        $BUF_record["nombre_seances"] = trim(substr($buffer, 131, 2));
        $BUF_record["nombre_diagnostics"] = trim(substr($buffer, 133, 2));
        $BUF_record["nombre_donnees_documentaires"] = trim(substr($buffer, 135, 2));
        $BUF_record["nombre_actes"] = trim(substr($buffer, 137, 3));
        $BUF_record["diagnostic_principal"] = trim(substr($buffer, 140, 8));
        $BUF_record["diagnostic_relie"] = trim(substr($buffer, 148, 8));
        $BUF_record["igs2"] = trim(substr($buffer, 156, 3));
        $BUF_record["confirmation_codage"] = trim(substr($buffer, 159, 1));
        $BUF_record["type_machine_rdth"] = trim(substr($buffer, 160, 1));
        $BUF_record["type_dosimetrie"] = trim(substr($buffer, 161, 1));
        $BUF_record["numero_innovation"] = trim(substr($buffer, 162, 15));
        $BUF_record["nombre_ivg_anterieures"] = trim(substr($buffer, 177, 2));
        $BUF_record["annee_ivg_precedente"] = trim(substr($buffer, 179, 4));
        $BUF_record["nombre_naissances_vivantes_anterieures"] = trim(substr($buffer, 187, 2));
        $BUF_record["filler"] = trim(substr($buffer, 189, 3));
        $BUF_start = 192;
        break;
    case "118" :
        $BUF_record["BUF_offsets"] = $rss_offsets_117;
        $BUF_record["no_rss"] = trim(substr($buffer, 27, 20));
        $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 47, 20));
        $BUF_record["no_rum"] = trim(substr($buffer, 67, 10));
        if ($last_BUF_rss !== $BUF_record["no_rss"]) {
            $last_BUF_rum = 0;
            $last_BUF_rss = $BUF_record["no_rss"];
        }
        $last_BUF_rum++;
        $BUF_record["no_rum"] = $last_BUF_rum;
        $BUF_record["date_naissance"] = trim(substr($buffer, 77, 8));
        $BUF_record["sexe"] = trim(substr($buffer, 85, 1));
        $BUF_record["unite_medicale"] = trim(substr($buffer, 86, 4));
        $BUF_record["type_autorisation_lit"] = trim(substr($buffer, 90, 2));
        $BUF_record["date_entree"] = trim(substr($buffer, 92, 8));
        $BUF_record["mode_entree"] = trim(substr($buffer, 100, 1));
        $BUF_record["provenance"] = trim(substr($buffer, 101, 1));
        $BUF_record["date_sortie"]= trim(substr($buffer, 102, 8));
        $BUF_record["mode_sortie"] = trim(substr($buffer, 110, 1));
        $BUF_record["destination"] = trim(substr($buffer, 111, 1));
        $BUF_record["code_postal"] = substr($buffer, 112, 5);
        $BUF_record["poids_bebe"] = trim(substr($buffer, 117, 4));
        $BUF_record["age_gestationnel"] = trim(substr($buffer, 121, 2));
        $BUF_record["date_dernieres_regles"] = trim(substr($buffer, 123, 8));
        $BUF_record["nombre_seances"] = trim(substr($buffer, 131, 2));
        $BUF_record["nombre_diagnostics"] = trim(substr($buffer, 133, 2));
        $BUF_record["nombre_donnees_documentaires"] = trim(substr($buffer, 135, 2));
        $BUF_record["nombre_actes"] = trim(substr($buffer, 137, 3));
        $BUF_record["diagnostic_principal"] = trim(substr($buffer, 140, 8));
        $BUF_record["diagnostic_relie"] = trim(substr($buffer, 148, 8));
        $BUF_record["igs2"] = trim(substr($buffer, 156, 3));
        $BUF_record["confirmation_codage"] = trim(substr($buffer, 159, 1));
        $BUF_record["type_machine_rdth"] = trim(substr($buffer, 160, 1));
        $BUF_record["type_dosimetrie"] = trim(substr($buffer, 161, 1));
        $BUF_record["numero_innovation"] = trim(substr($buffer, 162, 15));
        $BUF_record["filler"] = trim(substr($buffer, 177, 12));
        $BUF_start = 192;       
        break;
    case "119" :
        $BUF_record["BUF_offsets"] = $rss_offsets_119;
        $BUF_record["no_rss"] = trim(substr($buffer, 27, 20));
        $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 47, 20));
        $BUF_record["no_rum"] = trim(substr($buffer, 67, 10));
        if ($last_BUF_rss !== $BUF_record["no_rss"]) {
            $last_BUF_rum = 0;
            $last_BUF_rss = $BUF_record["no_rss"];
        }
        $last_BUF_rum++;
        $BUF_record["no_rum"] = $last_BUF_rum;
        $BUF_record["date_naissance"] = trim(substr($buffer, 77, 8));
        $BUF_record["sexe"] = trim(substr($buffer, 85, 1));
        $BUF_record["unite_medicale"] = trim(substr($buffer, 86, 4));
        $BUF_record["type_autorisation_lit"] = trim(substr($buffer, 90, 2));
        $BUF_record["date_entree"] = trim(substr($buffer, 92, 8));
        $BUF_record["mode_entree"] = trim(substr($buffer, 100, 1));
        $BUF_record["provenance"] = trim(substr($buffer, 101, 1));
        $BUF_record["date_sortie"]= trim(substr($buffer, 102, 8));
        $BUF_record["mode_sortie"] = trim(substr($buffer, 110, 1));
        $BUF_record["destination"] = trim(substr($buffer, 111, 1));
        $BUF_record["code_postal"] = substr($buffer, 112, 5);
        $BUF_record["poids_bebe"] = trim(substr($buffer, 117, 4));
        $BUF_record["age_gestationnel"] = trim(substr($buffer, 121, 2));
        $BUF_record["date_dernieres_regles"] = trim(substr($buffer, 123, 8));
        $BUF_record["nombre_seances"] = trim(substr($buffer, 131, 2));
        $BUF_record["nombre_diagnostics"] = trim(substr($buffer, 133, 2));
        $BUF_record["nombre_donnees_documentaires"] = trim(substr($buffer, 135, 2));
        $BUF_record["nombre_actes"] = trim(substr($buffer, 137, 3));
        $BUF_record["diagnostic_principal"] = trim(substr($buffer, 140, 8));
        $BUF_record["diagnostic_relie"] = trim(substr($buffer, 148, 8));
        $BUF_record["igs2"] = trim(substr($buffer, 156, 3));
        $BUF_record["confirmation_codage"] = trim(substr($buffer, 159, 1));
        $BUF_record["type_machine_rdth"] = trim(substr($buffer, 160, 1));
        $BUF_record["type_dosimetrie"] = trim(substr($buffer, 161, 1));
        $BUF_record["numero_innovation"] = trim(substr($buffer, 162, 15));
        $BUF_record["conversion_hp_hc"] = trim(substr($buffer, 177, 1));
        $BUF_record["raac"] = trim(substr($buffer, 178, 1));
        $BUF_record["filler"] = trim(substr($buffer, 179, 10));
        $BUF_start = 192;
        break; 
    case "120" :
        $BUF_record["BUF_offsets"] = $rss_offsets_120;
        $BUF_record["no_rss"] = trim(substr($buffer, 27, 20));
        $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 47, 20));
        $BUF_record["no_rum"] = trim(substr($buffer, 67, 10));
        if ($last_BUF_rss !== $BUF_record["no_rss"]) {
            $last_BUF_rum = 0;
            $last_BUF_rss = $BUF_record["no_rss"];
        }
        $last_BUF_rum++;
        $BUF_record["no_rum"] = $last_BUF_rum;
        $BUF_record["date_naissance"] = trim(substr($buffer, 77, 8));
        $BUF_record["sexe"] = trim(substr($buffer, 85, 1));
        $BUF_record["unite_medicale"] = trim(substr($buffer, 86, 4));
        $BUF_record["type_autorisation_lit"] = trim(substr($buffer, 90, 2));
        $BUF_record["date_entree"] = trim(substr($buffer, 92, 8));
        $BUF_record["mode_entree"] = trim(substr($buffer, 100, 1));
        $BUF_record["provenance"] = trim(substr($buffer, 101, 1));
        $BUF_record["date_sortie"]= trim(substr($buffer, 102, 8));
        $BUF_record["mode_sortie"] = trim(substr($buffer, 110, 1));
        $BUF_record["destination"] = trim(substr($buffer, 111, 1));
        $BUF_record["code_postal"] = substr($buffer, 112, 5);
        $BUF_record["poids_bebe"] = trim(substr($buffer, 117, 4));
        $BUF_record["age_gestationnel"] = trim(substr($buffer, 121, 2));
        $BUF_record["date_dernieres_regles"] = trim(substr($buffer, 123, 8));
        $BUF_record["nombre_seances"] = trim(substr($buffer, 131, 2));
        $BUF_record["nombre_diagnostics"] = trim(substr($buffer, 133, 2));
        $BUF_record["nombre_donnees_documentaires"] = trim(substr($buffer, 135, 2));
        $BUF_record["nombre_actes"] = trim(substr($buffer, 137, 3));
        $BUF_record["diagnostic_principal"] = trim(substr($buffer, 140, 8));
        $BUF_record["diagnostic_relie"] = trim(substr($buffer, 148, 8));
        $BUF_record["igs2"] = trim(substr($buffer, 156, 3));
        $BUF_record["confirmation_codage"] = trim(substr($buffer, 159, 1));
        $BUF_record["type_machine_rdth"] = trim(substr($buffer, 160, 1));
        $BUF_record["type_dosimetrie"] = trim(substr($buffer, 161, 1));
        $BUF_record["numero_innovation"] = trim(substr($buffer, 162, 15));
        $BUF_record["conversion_hp_hc"] = trim(substr($buffer, 177, 1));
        $BUF_record["raac"] = trim(substr($buffer, 178, 1));
        $BUF_record["filler"] = trim(substr($buffer, 179, 10));
        // integration nouveaux champs 2020
        $BUF_record["contexte_particulier"] = trim(substr($buffer, 179, 1));
        $BUF_record["administration_prod_rh"] = trim(substr($buffer, 180, 1));
        $BUF_record["rescrit_tarifaire"] = trim(substr($buffer, 181, 1));
        $BUF_record["categorie_nb_interventions"] = trim(substr($buffer, 182, 1));
        $BUF_record["filler"] = trim(substr($buffer, 183, 6));
        $BUF_start = 192;
        break; 
    case "121" :
        $BUF_record["BUF_offsets"] = $rss_offsets_121;
        $BUF_record["no_rss"] = trim(substr($buffer, 27, 20));
        $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 47, 20));
        $BUF_record["no_rum"] = trim(substr($buffer, 67, 10));
        if ($last_BUF_rss !== $BUF_record["no_rss"]) {
            $last_BUF_rum = 0;
            $last_BUF_rss = $BUF_record["no_rss"];
        }
        $last_BUF_rum++;
        $BUF_record["no_rum"] = $last_BUF_rum;
        $BUF_record["date_naissance"] = trim(substr($buffer, 77, 8));
        $BUF_record["sexe"] = trim(substr($buffer, 85, 1));
        $BUF_record["unite_medicale"] = trim(substr($buffer, 86, 4));
        $BUF_record["type_autorisation_lit"] = trim(substr($buffer, 90, 2));
        $BUF_record["date_entree"] = trim(substr($buffer, 92, 8));
        $BUF_record["mode_entree"] = trim(substr($buffer, 100, 1));
        $BUF_record["provenance"] = trim(substr($buffer, 101, 1));
        $BUF_record["date_sortie"]= trim(substr($buffer, 102, 8));
        $BUF_record["mode_sortie"] = trim(substr($buffer, 110, 1));
        $BUF_record["destination"] = trim(substr($buffer, 111, 1));
        $BUF_record["code_postal"] = substr($buffer, 112, 5);
        $BUF_record["poids_bebe"] = trim(substr($buffer, 117, 4));
        $BUF_record["age_gestationnel"] = trim(substr($buffer, 121, 2));
        $BUF_record["date_dernieres_regles"] = trim(substr($buffer, 123, 8));
        $BUF_record["nombre_seances"] = trim(substr($buffer, 131, 2));
        $BUF_record["nombre_diagnostics"] = trim(substr($buffer, 133, 2));
        $BUF_record["nombre_donnees_documentaires"] = trim(substr($buffer, 135, 2));
        $BUF_record["nombre_actes"] = trim(substr($buffer, 137, 3));
        $BUF_record["diagnostic_principal"] = trim(substr($buffer, 140, 8));
        $BUF_record["diagnostic_relie"] = trim(substr($buffer, 148, 8));
        $BUF_record["igs2"] = trim(substr($buffer, 156, 3));
        $BUF_record["confirmation_codage"] = trim(substr($buffer, 159, 1));
        $BUF_record["type_machine_rdth"] = trim(substr($buffer, 160, 1));
        $BUF_record["type_dosimetrie"] = trim(substr($buffer, 161, 1));
        $BUF_record["numero_innovation"] = trim(substr($buffer, 162, 15));
        $BUF_record["conversion_hp_hc"] = trim(substr($buffer, 177, 1));
        $BUF_record["raac"] = trim(substr($buffer, 178, 1));
        $BUF_record["filler"] = trim(substr($buffer, 179, 10));
        // integration nouveaux champs 2020
        $BUF_record["contexte_particulier"] = trim(substr($buffer, 179, 1));
        $BUF_record["administration_prod_rh"] = trim(substr($buffer, 180, 1));
        $BUF_record["rescrit_tarifaire"] = trim(substr($buffer, 181, 1));
        $BUF_record["categorie_nb_interventions"] = trim(substr($buffer, 182, 1));
        $BUF_record["np"] = trim(substr($buffer, 183, 1));
        $BUF_record["filler"] = trim(substr($buffer, 184, 6));
        $BUF_start = 192;
        break;    			
    case "122" :
        $BUF_record["BUF_offsets"] = $rss_offsets_122;
        $BUF_record["no_rss"] = trim(substr($buffer, 27, 20));
        $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 47, 20));
        $BUF_record["no_rum"] = trim(substr($buffer, 67, 10));
        if ($last_BUF_rss !== $BUF_record["no_rss"]) {
            $last_BUF_rum = 0;
            $last_BUF_rss = $BUF_record["no_rss"];
        }
        $last_BUF_rum++;
        $BUF_record["no_rum"] = $last_BUF_rum;
        $BUF_record["date_naissance"] = trim(substr($buffer, 77, 8));
        $BUF_record["sexe"] = trim(substr($buffer, 85, 1));
        $BUF_record["unite_medicale"] = trim(substr($buffer, 86, 4));
        $BUF_record["type_autorisation_lit"] = trim(substr($buffer, 90, 2));
        $BUF_record["date_entree"] = trim(substr($buffer, 92, 8));
        $BUF_record["mode_entree"] = trim(substr($buffer, 100, 1));
        $BUF_record["provenance"] = trim(substr($buffer, 101, 1));
        $BUF_record["date_sortie"]= trim(substr($buffer, 102, 8));
        $BUF_record["mode_sortie"] = trim(substr($buffer, 110, 1));
        $BUF_record["destination"] = trim(substr($buffer, 111, 1));
        $BUF_record["code_postal"] = substr($buffer, 112, 5);
        $BUF_record["poids_bebe"] = trim(substr($buffer, 117, 4));
        $BUF_record["age_gestationnel"] = trim(substr($buffer, 121, 2));
        $BUF_record["date_dernieres_regles"] = trim(substr($buffer, 123, 8));
        $BUF_record["nombre_seances"] = trim(substr($buffer, 131, 2));
        $BUF_record["nombre_diagnostics"] = trim(substr($buffer, 133, 2));
        $BUF_record["nombre_donnees_documentaires"] = trim(substr($buffer, 135, 2));
        $BUF_record["nombre_actes"] = trim(substr($buffer, 137, 3));
        $BUF_record["diagnostic_principal"] = trim(substr($buffer, 140, 8));
        $BUF_record["diagnostic_relie"] = trim(substr($buffer, 148, 8));
        $BUF_record["igs2"] = trim(substr($buffer, 156, 3));
        $BUF_record["confirmation_codage"] = trim(substr($buffer, 159, 1));
        $BUF_record["type_machine_rdth"] = trim(substr($buffer, 160, 1));
        $BUF_record["type_dosimetrie"] = trim(substr($buffer, 161, 1));
        $BUF_record["numero_innovation"] = trim(substr($buffer, 162, 15));
        $BUF_record["conversion_hp_hc"] = trim(substr($buffer, 177, 1));
        $BUF_record["raac"] = trim(substr($buffer, 178, 1));
        $BUF_record["filler"] = trim(substr($buffer, 179, 10));
        $BUF_record["contexte_particulier"] = trim(substr($buffer, 179, 1));
        $BUF_record["administration_prod_rh"] = trim(substr($buffer, 180, 1));
        $BUF_record["rescrit_tarifaire"] = trim(substr($buffer, 181, 1));
        $BUF_record["categorie_nb_interventions"] = trim(substr($buffer, 182, 1));
        $BUF_record["np"] = trim(substr($buffer, 183, 1));
        $BUF_record["passage_urgences"] = trim(substr($buffer, 184, 1));
        $BUF_record["filler"] = trim(substr($buffer, 185, 4));
        $BUF_start = 192;
        break;    			
    default :
        $BUF_record["BUF_offsets"] = $rss_offsets_121;
        $BUF_record["no_rss"] = trim(substr($buffer, 27, 20));
        $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 47, 20));
        $BUF_record["no_rum"] = trim(substr($buffer, 67, 10));
        if ($last_BUF_rss !== $BUF_record["no_rss"]) {
            $last_BUF_rum = 0;
            $last_BUF_rss = $BUF_record["no_rss"];
        }
        $last_BUF_rum++;
        $BUF_record["no_rum"] = $last_BUF_rum;
        $BUF_record["date_naissance"] = trim(substr($buffer, 77, 8));
        $BUF_record["sexe"] = trim(substr($buffer, 85, 1));
        $BUF_record["unite_medicale"] = trim(substr($buffer, 86, 4));
        $BUF_record["type_autorisation_lit"] = trim(substr($buffer, 90, 2));
        $BUF_record["date_entree"] = trim(substr($buffer, 92, 8));
        $BUF_record["mode_entree"] = trim(substr($buffer, 100, 1));
        $BUF_record["provenance"] = trim(substr($buffer, 101, 1));
        $BUF_record["date_sortie"]= trim(substr($buffer, 102, 8));
        $BUF_record["mode_sortie"] = trim(substr($buffer, 110, 1));
        $BUF_record["destination"] = trim(substr($buffer, 111, 1));
        $BUF_record["code_postal"] = substr($buffer, 112, 5);
        $BUF_record["poids_bebe"] = trim(substr($buffer, 117, 4));
        $BUF_record["age_gestationnel"] = trim(substr($buffer, 121, 2));
        $BUF_record["date_dernieres_regles"] = trim(substr($buffer, 123, 8));
        $BUF_record["nombre_seances"] = trim(substr($buffer, 131, 2));
        $BUF_record["nombre_diagnostics"] = trim(substr($buffer, 133, 2));
        $BUF_record["nombre_donnees_documentaires"] = trim(substr($buffer, 135, 2));
        $BUF_record["nombre_actes"] = trim(substr($buffer, 137, 3));
        $BUF_record["diagnostic_principal"] = trim(substr($buffer, 140, 8));
        $BUF_record["diagnostic_relie"] = trim(substr($buffer, 148, 8));
        $BUF_record["igs2"] = trim(substr($buffer, 156, 3));
        $BUF_record["confirmation_codage"] = trim(substr($buffer, 159, 1));
        $BUF_record["type_machine_rdth"] = trim(substr($buffer, 160, 1));
        $BUF_record["type_dosimetrie"] = trim(substr($buffer, 161, 1));
        $BUF_record["numero_innovation"] = trim(substr($buffer, 162, 15));
        $BUF_record["conversion_hp_hc"] = trim(substr($buffer, 177, 1));
        $BUF_record["raac"] = trim(substr($buffer, 178, 1));
        // integration nouveaux champs 2020
        $BUF_record["contexte_particulier"] = trim(substr($buffer, 179, 1));
        $BUF_record["administration_prod_rh"] = trim(substr($buffer, 180, 1));
        $BUF_record["rescrit_tarifaire"] = trim(substr($buffer, 181, 1));
        $BUF_record["categorie_nb_interventions"] = trim(substr($buffer, 182, 1));
        $BUF_record["filler"] = trim(substr($buffer, 183, 6));
        $BUF_start = 192;           
    }
    
    // constante RSS dans le n° de RSS
    $position = strpos($BUF_record["no_rss"], 'RSS');
    if ($position !== false) {
        $BUF_record["no_rss"] = str_replace("RSS","000",$BUF_record["no_rss"]);
    }
    
    // Bourrage à gauche avec des zéros sur zones numériques
    $BUF_record["igs2"] = str_pad($BUF_record["igs2"], 3, "0", STR_PAD_LEFT);
    $BUF_record["nombre_actes"] = str_pad($BUF_record["nombre_actes"], 3, "0", STR_PAD_LEFT);
    $BUF_record["nombre_diagnostics"] = str_pad($BUF_record["nombre_diagnostics"], 2, "0", STR_PAD_LEFT);
    $BUF_record["nombre_donnees_documentaires"] = str_pad($BUF_record["nombre_donnees_documentaires"], 2, "0", STR_PAD_LEFT);
    $BUF_record["nombre_seances"] = str_pad($BUF_record["nombre_seances"], 2, "0", STR_PAD_LEFT);
    $BUF_record["nombre_ivg_anterieures"] = str_pad($BUF_record["nombre_ivg_anterieures"], 2, "0", STR_PAD_LEFT);
    $BUF_record["nombre_naissances_vivantes_anterieures"] = str_pad($BUF_record["nombre_naissances_vivantes_anterieures"], 2, "0", STR_PAD_LEFT);
    
    // remplacement blancs par 0 dans code postal
    $BUF_record["code_postal"] = str_ireplace(" ", "0", $BUF_record["code_postal"]);
    $BUF_record["code_postal"] = str_ireplace("O", "0", $BUF_record["code_postal"]);
    
    //Attention, si plus de 99 actes
    if (substr($BUF_record["nombre_actes"], 0, 1) != "0") {
        if (substr($BUF_record["diagnostic_principal"], 0, 1) >= "0" && substr($BUF_record["diagnostic_principal"], 0, 1) <= "9") {
            $BUF_record["nombre_actes"] = $BUF_record["nombre_actes"] . substr($BUF_record["diagnostic_principal"], 0, 1);
            $BUF_record["diagnostic_principal"] = substr($BUF_record["diagnostic_principal"], 1);
        }
    }

    
    if ($qAD == TRUE) {
        for ($i = 1; $i <= get_num($BUF_record["nombre_diagnostics"]); $i++) {
            $BUF_diagnostic_associe = trim(substr($buffer, $BUF_start, 8));
            $BUF_record["diags"][$i] = $BUF_diagnostic_associe;
            $BUF_record["diags_offset"][$i] = $BUF_start;
            $BUF_record["diags_len"][$i] = 8;
            $BUF_start = $BUF_start + 8;
        }
        for ($i = 1; $i <= get_num($BUF_record["nombre_donnees_documentaires"]); $i++) {
            $BUF_diagnostic_documentaire = trim(substr($buffer, $BUF_start, 8));
            $BUF_record["diagsdoc"][$i] = $BUF_diagnostic_documentaire;
            $BUF_record["diagsdoc_offset"][$i] = $BUF_start;
            $BUF_record["diagsdoc_len"][$i] = 8;
            $BUF_start = $BUF_start + 8;
        }
        for ($i = 1; $i <= get_num($BUF_record["nombre_actes"]); $i++) {
            $BUF_record["offset_format"] = 0;
            switch ($BUF_record["version_format"]) {
                case "110" :
                    $buf_len = 10;
                    $BUF_acte = substr($buffer, $BUF_start, 10);
                    $BUF_acte = $BUF_record["date_sortie"] . substr($BUF_acte, 0, 8) . "1";
                    $BUF_start = $BUF_start + 10;
                    break;
                case "111" :
                case "112" :
                case "113" :
                case "114" :
                case "115" :
                case "116" :
                    $buf_len = 26;
                    $BUF_acte = substr($buffer, $BUF_start, 26);
                    if (trim(substr($BUF_acte, 0, 8)) == "") {
                        $BUF_acte = $BUF_record["date_sortie"] . substr($BUF_acte, 8, 18);
                    }
                    $BUF_start = $BUF_start + 26;
                    break;
                default :
                    $buf_len = 29;
                    $BUF_record["offset_format"] = 3;
                    $BUF_acte = substr($buffer, $BUF_start, $buf_len);
                    if (trim(substr($BUF_acte, 0, 8)) == "") {
                        $BUF_acte = $BUF_record["date_sortie"] . substr($BUF_acte, 8, 21);
                    }
                    $BUF_start = $BUF_start + $buf_len;
            }
            
            $BUF_record["actes"][$i] = $BUF_acte;
            $BUF_record["actes_offset"][$i] = $BUF_start;
            $BUF_record["actes_len"][$i] = $buf_len;
        }
    }
    
    
    return $BUF_record;
        

}



function read_rum_partial_line($buffer) {


    $BUF_record = array();

    $buffer = Encoding::removeBOM($buffer);

    if (is_entete_empty($buffer)){
        $BUF_record["type_enregistrement"] = "ENTETE";
        return $BUF_record;
    }
 
    if (trim(substr($buffer, 27, 5) == "NRSS0")) {
        $BUF_record["type_enregistrement"] = "NONE";
        return $BUF_record;
    }
    
    $BUF_record["type_enregistrement"] = "RUM";

    $BUF_record["no_rss"] = "";
    $BUF_record["version_format"] = trim(substr($buffer, 9, 3));
    
    switch ($BUF_record["version_format"]) {
        case "110" :
            $BUF_record["no_rss"] = trim(substr($buffer, 27, 7));
            $BUF_record["date_sortie"] = trim(substr($buffer, 57, 8));
            $BUF_record["no_sejour_administratif"] = "";
            break;
        case "111" :
            $BUF_record["no_rss"] = trim(substr($buffer, 27, 7));
            $BUF_record["date_sortie"] = trim(substr($buffer, 82, 8));
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 34, 20));
            break;
        default : // depuis format 113
            $BUF_record["no_rss"] = trim(substr($buffer, 27, 20));
            $BUF_record["date_sortie"]= trim(substr($buffer, 102, 8));
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 47, 20));
            
    }
    
    // constante RSS dans le n° de RSS
    $position = strpos($BUF_record["no_rss"], 'RSS');
    if ($position !== false) {
        $BUF_record["no_rss"] = str_replace("RSS","000",$BUF_record["no_rss"]);
    }
    
    return $BUF_record;
}




function read_rsf_line($buffer, $qA=TRUE, $qB=TRUE, $qP=TRUE, $qM=TRUE, $qH=true, $qI=true) {

    global $ENV_TYPEETS;
    global $ENV_OPTPMSI_FSD_B;
    
    global $max_ACE;

    global $rsf_last_RSS;

    global $rsf_offsets_2006_A;
    global $rsf_offsets_2006_B;
    global $rsf_offsets_2006_P;
    global $rsf_offsets_2006_M;
    global $rsf_offsets_2008_A;
    global $rsf_offsets_2008_B;
    global $rsf_offsets_2008_P;
    global $rsf_offsets_2008_M;
    global $rsf_offsets_2008B_M;

    global $rsf_offsets_2015_A;
    global $rsf_offsets_2016_A;
    global $rsf_offsets_2017_A;
    global $rsf_offsets_2017_B;
    global $rsf_offsets_2017_P;
    global $rsf_offsets_2017_H;
	global $rsf_offsets_2017_I;
    global $rsf_offsets_2017_M;
    
    global $rsf_ace_offsets_2009_A;
    
    global $rsf_ace_offsets_2008_A;

    global $rsf_ace_offsets_2016_B;
    global $rsf_ace_offsets_2008_B;
    global $rsf_ace_offsets_2008_C;

    global $rsf_ace_offsets_2016_M;
    global $rsf_ace_offsets_2008_M;
    
    global $rsf_ace_offsets_2007_A;
    global $rsf_ace_offsets_2007_C;
    global $rsf_ace_offsets_2007_M;
    global $rsf_ace_offsets_2017_A;
    global $rsf_ace_offsets_2017_M;
    global $rsf_ace_offsets_2017_B;
    
    global $current_rsfa_index;

    $BUF_record = array();
    
    $BUF_record["ok"] = FALSE;

    $buffer = Encoding::removeBOM($buffer);

    $buf_len = strlen($buffer);

     
    if (is_entete_empty($buffer)){
        $BUF_record["type_enregistrement"] = "ENTETE";
        return $BUF_record;
    }
    
    // Types d'enregistrements RSF (2023) :
    // A = Début de facture
    // B = Prestations Hospitalière
    // C = Honoraires
    // H = Médicament
    // I = Interruptiond de Séjour
    // P = Prothèses
    $BUF_record["type_enregistrement"] = trim(substr($buffer, 0, 1));
    
    // Special Saint laurent pb décalages
    if ($BUF_record["type_enregistrement"] == "A" && substr($buffer, 0, 10) == "A350002192") {
        if (trim(substr($buffer, 34, 25)) == "") {
            $BUF_record["type_enregistrement"] = "IGNORE";
        }
    }
    
    /////////////////////////    A = Début de facture     ///////////////////////// 
    if ($BUF_record["type_enregistrement"] == "A" && $qA == TRUE) {
    
        $current_rsfa_index++;
        
        if ($ENV_TYPEETS == "1") {
            $BUF_141 = trim(substr($buffer, 141, 100));
            $BUF_158 = trim(substr($buffer, 158, 100));
            $BUF_168 = trim(substr($buffer, 168, 100)); //Format de mars 2015
            if ($buf_len > 240) {
                $BUF_version = "2019";
            } else if ($buf_len > 220) {
                $BUF_version = "2017";
            } else if ($BUF_141 == "") {
                $BUF_version = "2006";
            } else if ($BUF_158 == "") {
                $BUF_version = "2008";
            } else if ($BUF_168 == "") {
                $BUF_version = "2012";
            } else {
                $BUF_version = "2015";
            }
        }
        else {
            $BUF_137 = trim(substr($buffer, 136, 100));
            $BUF_146 = trim(substr($buffer, 146, 100)); //Format de mars 2015
            $BUF_2016 = trim(substr($buffer, 66, 8)); //Format de mars 2016
            $BUF_2016_OK = "";
            if (substr($BUF_2016,4,2) == "20"  && substr($BUF_2016,2,2) < 13 && substr($BUF_2016,0,2) < 32  ) {
                $BUF_2016_OK = "OK";
            }           
            if ($buf_len > 280) {
                $BUF_version = "ACE2019";
            } else if ($buf_len > 260) {
                $BUF_version = "ACE2018";
            } else if ($buf_len > 200) {
                $BUF_version = "ACE2017";
            } else if ($BUF_146 != "") {
                                
                if ($BUF_2016_OK == "OK") {
                    $BUF_version = "ACE2016";
                }
                else {
                    $BUF_version = "ACE2015";
                }   

            } else if ($BUF_137 != "") {
                $BUF_version = "ACE2007";
                $annee_sortie = trim(substr($buffer, 69, 4));
                // if ($max_ACE == "2009" || $annee_sortie == "2008" || $annee_sortie == "2009" || $annee_sortie == "2010" || $annee_sortie == "2011") {
                if ($max_ACE == "2009" || intval($annee_sortie) >= 2008) {
                    $BUF_version = "ACE2009";
                    $max_ACE = "2009";
                }
                else {
                    $annee_sortie = trim(substr($buffer, 74, 4));
                    if ($annee_sortie == "2006" || $annee_sortie == "2007" || $annee_sortie == "2008") {
                        $BUF_version = "ACE2007I";
                    }
                }
            }
            else {
                $BUF_version = "ACE2008";
            }
        }
    
        $BUF_record["finess"] = trim(substr($buffer, 1, 9));
        $BUF_record["no_rss"] = "";
        // Initialisation champs
        $BUF_record["immatriculation_assure"]       = "";
        $BUF_record["cle_immatriculation_assure"]   = "";
        $BUF_record["grand_regime"]                 = "";
        $BUF_record["code_gestion"]                 = "";
        $BUF_record["date_naissance"]               = "";
        $BUF_record["sexe"]                         = "";
        $BUF_record["no_sejour_administratif"]      = "";
        $BUF_record["immatriculation_indiv"]        = "";
        $BUF_record["cle_immatriculation_indiv"]    = "";
        $BUF_record["justificatif_exo"]             = "";
        $BUF_record["code_pec_fj"]                  = "";
        $BUF_record["nature_assurance"]             = "";
        $BUF_record["type_contrat_oc"]              = "";
        $BUF_record["code_pec"]                     = "";
        $BUF_record["motif_non_facturation"]        = "";
        $BUF_record["facturation_18euros"]          = "";
        $BUF_record["nombre_venues"]                = "";
        $BUF_record["montant_tm"]                   = "";
        $BUF_record["montant_fj"]                   = "";
        $BUF_record["total_remboursable_amo"]       = "";
        $BUF_record["montant_parcours_soins"]       = "";
        $BUF_record["base_remboursement_c"]         = "";
        $BUF_record["taux_remboursement_c"]         = "";
        $BUF_record["cmu"]                          = "";
        $BUF_record["no_sejour_administratif_mere"] = "";
        $BUF_record["hospit_nouveau_ne"]            = "";
        $BUF_record["prelevement_organe"]           = "";
        $BUF_record["date_hospitalisation"]         = "";
        $BUF_record["total_remboursable_amc"]       = "";
        $BUF_record["code_participation_assure"]    = "";
        $BUF_record["no_entree"]                    = "";
        $BUF_record["rang_naissance"]               = "";
        $BUF_record["rang_beneficiaire"]            = "";
        $BUF_record["no_caisse_gestionnaire"]       = "";
        $BUF_record["no_centre_gestionnaire"]       = "";
        $BUF_record["confirmation_pec"]             = "";
        $BUF_record["no_at_date_adc"]               = "";
        $BUF_record["no_organisme_complementaire"]  = "";
        $BUF_record["nature_piece_justificative"]   = "";
        $BUF_record["date_pec"]                     = "";
        $BUF_record["date_debut_pec"]               = "";
        $BUF_record["delivre_par"]                  = "";
        $BUF_record["regime_assure"]                = "";
        $BUF_record["top_eclatement_flux_etab"]     = "";
        $BUF_record["date_entree"]                  = "";
        $BUF_record["date_sortie"]                  = "";
        // nouveautés 2018
        $BUF_record["montant_total_sejour_patient"] = "";    // montant facturé au titre de la part patient
        $BUF_record["nb_rejet_amo"]                 = "";    // nombre de fois ou FT AMO a été refetée (0 à 9)
        $BUF_record["date_facture_amo"]             = "";    // date de l'envoi de la FT AMO
        $BUF_record["date_facture_amc"]             = "";    // date de l'envoi de la FT AMC
        $BUF_record["date_facture_patient"]         = "";    // date de l'envoi de la FT patient
        $BUF_record["date_paiement_amo"]            = "";    // date à laquelle la FT AMO est payée en totalité (statut S16)
        $BUF_record["date_paiement_amc"]            = "";    // date à laquelle la FT AMC est payée en totalité (statut S16)
        $BUF_record["date_paiement_patient"]        = "";    // date à laquelle la FT patient est payée en totalité (statut S16)
        $BUF_record["statut_ft_amo"]                = "";    // 0:avant validation, 1:validée, 2:NiNi, 3:payée, 9:S/O
        $BUF_record["statut_ft_amc"]                = "";    // 0:avant validation, 1:validée, 2:NiNi, 3:payée, 9:S/O
        $BUF_record["statut_ft_patient"]            = "";    // 0:avant validation, 1:validée, 2:NiNi, 3:payée, 9:S/O
        $BUF_record["pays_amo"]                     = "";    // Code INSEE à 5 chiffres, sans les deux premiers chiffres 99 ou code ISO 3166-1 Alpha-3. Blanc ou 000 par défaut
        // nouveautés 2019
        $BUF_record["no_ipp"]                       = "";    // Numéro d'identification permanent du patient


        $BUF_record["no_facture_sejour_mere"]       = "";    // Numéro d'identification permanent du patient


        switch ($BUF_version) {
        case "2019" :
            $BUF_record["no_ipp"] = trim(substr($buffer, 221, 20));
        case "2017" :
        case "2019" :
            $BUF_record["BUF_offsets"] = $rsf_offsets_2017_A;
        
            $BUF_record["no_rss"] = trim(substr($buffer, 19, 20));
            $BUF_record["sexe"] = trim(substr($buffer, 39, 1));
            $BUF_record["civilite"] = trim(substr($buffer, 40, 1));
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 41, 13));
            $BUF_record["cle_immatriculation_assure"] = trim(substr($buffer, 54, 2));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 56, 3));
            $BUF_record["no_facture"] = trim(substr($buffer, 59, 9));
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 59, 9));
            $BUF_record["immatriculation_indiv"] = trim(substr($buffer, 68, 13));
            $BUF_record["cle_immatriculation_indiv"] = trim(substr($buffer, 81, 2));
            $BUF_record["nature_operation"] = trim(substr($buffer, 84, 1));
            $BUF_record["nature_assurance"] = trim(substr($buffer, 85, 2));
            $BUF_record["type_contrat_oc"] = trim(substr($buffer, 87, 2));
            $BUF_record["justificatif_exo"] = trim(substr($buffer, 89, 1));
            $BUF_record["code_pec"] = trim(substr($buffer, 91, 1));
            $BUF_record["grand_regime"] = trim(substr($buffer, 93, 2));
            $BUF_record["date_naissance"] = trim(substr($buffer, 95, 8));
            $BUF_record["rang_naissance"] = trim(substr($buffer, 103, 1));
            $BUF_record["date_entree"] = trim(substr($buffer, 104, 8));
            $BUF_record["date_sortie"] = trim(substr($buffer, 112, 8));
            $BUF_record["code_postal"]  = trim(substr($buffer, 120, 5));
            $BUF_record["base_remboursement_c"] = trim(substr($buffer, 125, 8));
            $BUF_record["total_remboursable_amo"] = trim(substr($buffer, 133, 8));
            $BUF_record["total_honoraires_factures"] = trim(substr($buffer, 141, 8));
            $BUF_record["total_honoraires_remboursable"] = trim(substr($buffer, 149, 8));
            $BUF_record["total_assure_avant_oc"] = trim(substr($buffer, 157, 8));
            $BUF_record["total_remboursable_oc_ph"] = trim(substr($buffer, 165, 8));
            $BUF_record["total_remboursable_oc_honoraires"] = trim(substr($buffer, 173, 8));
            $BUF_record["total_facture_ph"] = trim(substr($buffer, 181, 8));
            $BUF_record["etat_liquidation"] = trim(substr($buffer, 189, 1));
            $BUF_record["pat_benef_cmu"] = trim(substr($buffer, 190, 1));
            $BUF_record["code_gestion"] = trim(substr($buffer, 191, 2));
            $BUF_record["no_facture_sejour_mere"] = trim(substr($buffer, 193, 9));
            $BUF_record["no_organisme_complementaire"] = trim(substr($buffer, 202, 10)); // format RSF 2015
            $BUF_record["no_at_date_adc"] = trim(substr($buffer, 212, 9)); // format RSF 2015
            
            $BUF_record["ok"] = TRUE;       
            break;
        case "2015" :
            $BUF_record["BUF_offsets"] = $rsf_offsets_2015_A;
        
            $BUF_record["no_rss"] = trim(substr($buffer, 10, 20));
            $BUF_record["sexe"] = trim(substr($buffer, 30, 1));
            $BUF_record["civilite"] = trim(substr($buffer, 31, 1));
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 32, 13));
            $BUF_record["cle_immatriculation_assure"] = trim(substr($buffer, 45, 2));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 47, 3));
            $BUF_record["no_facture"] = trim(substr($buffer, 50, 9));
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 50, 9));
            $BUF_record["nature_operation"] = trim(substr($buffer, 59, 1));
            $BUF_record["nature_assurance"] = trim(substr($buffer, 60, 2));
            $BUF_record["type_contrat_oc"] = trim(substr($buffer, 62, 2));
            $BUF_record["justificatif_exo"] = trim(substr($buffer, 64, 1));
            $BUF_record["code_pec"] = trim(substr($buffer, 65, 1));
            $BUF_record["grand_regime"] = trim(substr($buffer, 66, 2));
            $BUF_record["date_naissance"] = trim(substr($buffer, 68, 8));
            $BUF_record["rang_naissance"] = trim(substr($buffer, 76, 1));
            $BUF_record["date_entree"] = trim(substr($buffer, 77, 8));
            $BUF_record["date_sortie"] = trim(substr($buffer, 85, 8));
            $BUF_record["base_remboursement_c"] = trim(substr($buffer, 93, 8));
            $BUF_record["total_remboursable_amo"] = trim(substr($buffer, 101, 8));
            $BUF_record["total_honoraires_factures"] = trim(substr($buffer, 109, 8));
            $BUF_record["total_honoraires_remboursable"] = trim(substr($buffer, 117, 8));
            $BUF_record["total_assure_avant_oc"] = trim(substr($buffer, 125, 8));
            $BUF_record["total_remboursable_oc_ph"] = trim(substr($buffer, 133, 8));
            $BUF_record["total_remboursable_oc_honoraires"] = trim(substr($buffer, 141, 8));
            $BUF_record["total_facture_ph"] = trim(substr($buffer, 149, 8));
            $BUF_record["etat_liquidation"] = trim(substr($buffer, 157, 1));
            $BUF_record["pat_benef_cmu"] = trim(substr($buffer, 158, 1));
            $BUF_record["no_facture_sejour_mere"] = trim(substr($buffer, 159, 9));
            $BUF_record["no_organisme_complementaire"] = trim(substr($buffer, 168, 10)); // format RSF 2015
            $BUF_record["no_at_date_adc"] = trim(substr($buffer, 178, 10)); // format RSF 2015
            
            $BUF_record["ok"] = TRUE;       
            break;
        case "2012" :
            $BUF_record["BUF_offsets"] = $rsf_offsets_2008_A;
        
            $BUF_record["no_rss"] = trim(substr($buffer, 10, 20));
            $BUF_record["sexe"] = trim(substr($buffer, 30, 1));
            $BUF_record["civilite"] = trim(substr($buffer, 31, 1));
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 32, 13));
            $BUF_record["cle_immatriculation_assure"] = trim(substr($buffer, 45, 2));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 47, 3));
            $BUF_record["no_facture"] = trim(substr($buffer, 50, 9));
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 50, 9));
            $BUF_record["nature_operation"] = trim(substr($buffer, 59, 1));
            $BUF_record["nature_assurance"] = trim(substr($buffer, 60, 2));
            $BUF_record["type_contrat_oc"] = trim(substr($buffer, 62, 2));
            $BUF_record["justificatif_exo"] = trim(substr($buffer, 64, 1));
            $BUF_record["code_pec"] = trim(substr($buffer, 65, 1));
            $BUF_record["grand_regime"] = trim(substr($buffer, 66, 2));
            $BUF_record["date_naissance"] = trim(substr($buffer, 68, 8));
            $BUF_record["rang_naissance"] = trim(substr($buffer, 76, 1));
            $BUF_record["date_entree"] = trim(substr($buffer, 77, 8));
            $BUF_record["date_sortie"] = trim(substr($buffer, 85, 8));
            $BUF_record["base_remboursement_c"] = trim(substr($buffer, 93, 8));
            $BUF_record["total_remboursable_amo"] = trim(substr($buffer, 101, 8));
            $BUF_record["total_honoraires_factures"] = trim(substr($buffer, 109, 8));
            $BUF_record["total_honoraires_remboursable"] = trim(substr($buffer, 117, 8));
            $BUF_record["total_assure_avant_oc"] = trim(substr($buffer, 125, 8));
            $BUF_record["total_remboursable_oc_ph"] = trim(substr($buffer, 133, 8));
            $BUF_record["total_remboursable_oc_honoraires"] = trim(substr($buffer, 141, 8));
            $BUF_record["total_facture_ph"] = trim(substr($buffer, 149, 8));
            $BUF_record["etat_liquidation"] = trim(substr($buffer, 157, 1));
            $BUF_record["pat_benef_cmu"] = trim(substr($buffer, 158, 1));
            $BUF_record["no_facture_sejour_mere"] = trim(substr($buffer, 159, 9));
            
            $BUF_record["ok"] = TRUE;       
            break;
        case "2008" :
            $BUF_record["BUF_offsets"] = $rsf_offsets_2008_A;
        
            $BUF_record["no_rss"] = trim(substr($buffer, 10, 20));
            $BUF_record["sexe"] = trim(substr($buffer, 30, 1));
            $BUF_record["civilite"] = trim(substr($buffer, 31, 1));
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 32, 13));
            $BUF_record["cle_immatriculation_assure"] = trim(substr($buffer, 45, 2));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 47, 3));
            $BUF_record["no_facture"] = trim(substr($buffer, 50, 9));
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 50, 9));
            $BUF_record["nature_operation"] = trim(substr($buffer, 59, 1));
            $BUF_record["nature_assurance"] = trim(substr($buffer, 60, 2));
            $BUF_record["type_contrat_oc"] = trim(substr($buffer, 62, 2));
            $BUF_record["justificatif_exo"] = trim(substr($buffer, 64, 1));
            $BUF_record["code_pec"] = trim(substr($buffer, 65, 1));
            $BUF_record["grand_regime"] = trim(substr($buffer, 66, 2));
            $BUF_record["date_naissance"] = trim(substr($buffer, 68, 8));
            $BUF_record["rang_naissance"] = trim(substr($buffer, 76, 1));
            $BUF_record["date_entree"] = trim(substr($buffer, 77, 8));
            $BUF_record["date_sortie"] = trim(substr($buffer, 85, 8));
            $BUF_record["base_remboursement_c"] = trim(substr($buffer, 93, 8));
            $BUF_record["total_remboursable_amo"] = trim(substr($buffer, 101, 8));
            $BUF_record["total_honoraires_factures"] = trim(substr($buffer, 109, 8));
            $BUF_record["total_honoraires_remboursable"] = trim(substr($buffer, 117, 8));
            $BUF_record["total_assure_avant_oc"] = trim(substr($buffer, 125, 8));
            $BUF_record["total_remboursable_oc_ph"] = trim(substr($buffer, 133, 8));
            $BUF_record["total_remboursable_oc_honoraires"] = trim(substr($buffer, 141, 8));
            $BUF_record["total_facture_ph"] = trim(substr($buffer, 149, 8));
            $BUF_record["etat_liquidation"] = trim(substr($buffer, 157, 1));
        
            
            $BUF_record["ok"] = TRUE;       
            break;
        case "2006" :
            $BUF_record["BUF_offsets"] = $rsf_offsets_2006_A;
            
            $BUF_record["no_rss"] = trim(substr($buffer, 10, 7));
            $BUF_record["sexe"] = trim(substr($buffer, 17, 1));
            $BUF_record["civilite"] = trim(substr($buffer, 18, 1));
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 19, 13));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 32, 3));
            $BUF_record["nature_operation"] = trim(substr($buffer, 35, 1));
            $BUF_record["nature_assurance"] = trim(substr($buffer, 36, 2));
            $BUF_record["justificatif_exo"] = trim(substr($buffer, 38, 1));
            $BUF_record["code_pec"] = trim(substr($buffer, 39, 1));
            $BUF_record["no_facture"] = trim(substr($buffer, 40, 9));
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 40, 9));
            $BUF_record["grand_regime"] = trim(substr($buffer, 49, 2));
            $BUF_record["date_naissance"] = trim(substr($buffer, 51, 8));
            $BUF_record["rang_naissance"] = trim(substr($buffer, 59, 1));
            $BUF_record["date_entree"] = trim(substr($buffer, 60, 8));
            $BUF_record["date_sortie"] = trim(substr($buffer, 68, 8));
            $BUF_record["base_remboursement_c"] = trim(substr($buffer, 76, 8));
            $BUF_record["total_remboursable_amo"] = trim(substr($buffer, 84, 8));
            $BUF_record["total_honoraires_factures"] = trim(substr($buffer, 92, 8));
            $BUF_record["total_honoraires_remboursable"] = trim(substr($buffer, 100, 8));
            $BUF_record["total_assure_avant_oc"] = trim(substr($buffer, 108, 8));
            $BUF_record["total_remboursable_oc_ph"] = trim(substr($buffer, 116, 8));
            $BUF_record["total_remboursable_oc_honoraires"] = trim(substr($buffer, 124, 8));
            $BUF_record["total_facture_ph"] = trim(substr($buffer, 132, 8));
            
            if (get_numrss($BUF_record["no_rss"]) == 0) {
                // $BUF_record["no_rss"] = trim($BUF_record["no_facture"] + 99000000000);
                $BUF_record["no_rss"] = '9' . str_pad(ltrim($BUF_record["no_facture"], '0'), 8, '0', STR_PAD_LEFT);
            }
            
            $BUF_record["ok"] = TRUE;       
            break;
        case "ACE2019" :
            $BUF_record["no_ipp"] = trim(substr($buffer, 265, 20));
        case "ACE2018" :
            $BUF_record["BUF_offsets"] = $rsf_ace_offsets_2017_A;
        
            $BUF_record["no_rss"] = 0;
            $BUF_record["sexe"] = trim(substr($buffer, 19, 1));
            $BUF_record["civilite"] = trim(substr($buffer, 20, 1));
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 21, 13));
            $BUF_record["cle_immatriculation_assure"] = trim(substr($buffer, 34, 2));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 36, 3));
            $BUF_record["no_facture"] = trim(substr($buffer, 301, 9));
            if ($BUF_record["no_facture"] == "") {
                $BUF_record["no_facture"] = trim(substr($buffer, 39, 9));
            }
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 39, 9));
            $BUF_record["immatriculation_indiv"] = trim(substr($buffer, 48, 13));
            $BUF_record["cle_immatriculation_indiv"] = trim(substr($buffer, 61, 2));
            $BUF_record["parcours_soins"] = trim(substr($buffer, 63, 1));
            $BUF_record["nature_operation"] = trim(substr($buffer, 64, 1));
            $BUF_record["nature_assurance"] = trim(substr($buffer, 65, 2));
            $BUF_record["type_contrat_oc"] = trim(substr($buffer, 67, 2));
            $BUF_record["justificatif_exo"] = trim(substr($buffer, 69, 1));
            $BUF_record["code_pec"] = trim(substr($buffer, 70, 1));
            $BUF_record["motif_non_facturation"] = trim(substr($buffer, 72, 1));
            $BUF_record["grand_regime"] = trim(substr($buffer, 73, 2));
            $BUF_record["date_naissance"] = trim(substr($buffer, 75, 8));
            $BUF_record["rang_naissance"] = trim(substr($buffer, 83, 1));
            $BUF_record["date_entree"] = trim(substr($buffer, 84, 8));
            $BUF_record["date_sortie"] = trim(substr($buffer, 92, 8));
            $BUF_record["code_postal"] = trim(substr($buffer, 100, 5));
            $BUF_record["base_remboursement_c"] = trim(substr($buffer, 105, 8));
            $BUF_record["total_remboursable_amo"] = trim(substr($buffer, 113, 8));
            $BUF_record["total_honoraires_factures"] = trim(substr($buffer, 121, 8));
            $BUF_record["total_honoraires_remboursable"] = trim(substr($buffer, 129, 8));
            $BUF_record["total_assure_avant_oc"] = trim(substr($buffer, 137, 8));
            $BUF_record["total_remboursable_oc_ph"] = trim(substr($buffer, 145, 8));
            $BUF_record["total_remboursable_oc_honoraires"] = trim(substr($buffer, 153, 8));
            $BUF_record["total_facture_ph"] = trim(substr($buffer, 161, 8));
            $BUF_record["pat_benef_cmu"] = trim(substr($buffer, 170, 1));
            $BUF_record["valorise_fides"] = trim(substr($buffer, 171, 1));
            $BUF_record["code_gestion"] = trim(substr($buffer, 172, 2));
            $BUF_record["no_organisme_complementaire"] = trim(substr($buffer, 183, 10));        // format RSF-A 2015
            $BUF_record["no_at_date_adc"] = trim(substr($buffer, 193, 9));      // format RSF-A 2015
            // nouveautés 2018
            $BUF_record["montant_total_sejour_patient"] = trim(substr($buffer, 202, 8));
            $BUF_record["nb_rejet_amo"] = trim(substr($buffer, 210, 1));
            $BUF_record["date_facture_amo"] = trim(substr($buffer, 211, 8));
            $BUF_record["date_facture_amc"] = trim(substr($buffer, 219, 8));
            $BUF_record["date_facture_patient"] = trim(substr($buffer, 227, 8));
            $BUF_record["date_paiement_amo"] = trim(substr($buffer, 235, 8));
            $BUF_record["date_paiement_amc"] = trim(substr($buffer, 243, 8));
            $BUF_record["date_paiement_patient"] = trim(substr($buffer, 251, 8));
            $BUF_record["statut_ft_amo"] = trim(substr($buffer, 259, 1));
            $BUF_record["statut_ft_amc"] = trim(substr($buffer, 260, 1));
            $BUF_record["statut_ft_patient"] = trim(substr($buffer, 261, 1));
            $BUF_record["pays_amo"] = trim(substr($buffer, 262, 3));
            
            //if (get_numrss($BUF_record["no_rss"]) == 0) {
                // $BUF_record["no_rss"] = trim($current_rsfa_index + 99000000000);
                $BUF_record["no_rss"] = '9' . str_pad(trim($current_rsfa_index), 8, '0', STR_PAD_LEFT);
            //}
            $BUF_record["ok"] = TRUE;       
            break;
        case "ACE2017" :
            $BUF_record["BUF_offsets"] = $rsf_ace_offsets_2017_A;
        
            $BUF_record["no_rss"] = 0;
            $BUF_record["sexe"] = trim(substr($buffer, 19, 1));
            $BUF_record["civilite"] = trim(substr($buffer, 20, 1));
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 21, 13));
            $BUF_record["cle_immatriculation_assure"] = trim(substr($buffer, 34, 2));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 36, 3));
            $BUF_record["no_facture"] = trim(substr($buffer, 39, 9));
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 39, 9));
            $BUF_record["immatriculation_indiv"] = trim(substr($buffer, 48, 13));
            $BUF_record["cle_immatriculation_indiv"] = trim(substr($buffer, 61, 2));
            $BUF_record["parcours_soins"] = trim(substr($buffer, 63, 1));
            $BUF_record["nature_operation"] = trim(substr($buffer, 64, 1));
            $BUF_record["nature_assurance"] = trim(substr($buffer, 65, 2));
            $BUF_record["type_contrat_oc"] = trim(substr($buffer, 67, 2));
            $BUF_record["justificatif_exo"] = trim(substr($buffer, 69, 1));
            $BUF_record["code_pec"] = trim(substr($buffer, 70, 1));
            $BUF_record["motif_non_facturation"] = trim(substr($buffer, 72, 1));
            $BUF_record["grand_regime"] = trim(substr($buffer, 73, 2));
            $BUF_record["date_naissance"] = trim(substr($buffer, 75, 8));
            $BUF_record["rang_naissance"] = trim(substr($buffer, 83, 1));
            $BUF_record["date_entree"] = trim(substr($buffer, 84, 8));
            $BUF_record["date_sortie"] = trim(substr($buffer, 92, 8));
            $BUF_record["code_postal"] = trim(substr($buffer, 100, 5));
            $BUF_record["base_remboursement_c"] = trim(substr($buffer, 105, 8));
            $BUF_record["total_remboursable_amo"] = trim(substr($buffer, 113, 8));
            $BUF_record["total_honoraires_factures"] = trim(substr($buffer, 121, 8));
            $BUF_record["total_honoraires_remboursable"] = trim(substr($buffer, 129, 8));
            $BUF_record["total_assure_avant_oc"] = trim(substr($buffer, 137, 8));
            $BUF_record["total_remboursable_oc_ph"] = trim(substr($buffer, 145, 8));
            $BUF_record["total_remboursable_oc_honoraires"] = trim(substr($buffer, 153, 8));
            $BUF_record["total_facture_ph"] = trim(substr($buffer, 161, 8));
            $BUF_record["pat_benef_cmu"] = trim(substr($buffer, 170, 1));
            $BUF_record["valorise_fides"] = trim(substr($buffer, 171, 1));
            $BUF_record["code_gestion"] = trim(substr($buffer, 172, 2));
            $BUF_record["no_organisme_complementaire"] = trim(substr($buffer, 183, 10));        // format RSF-A 2015
            $BUF_record["no_at_date_adc"] = trim(substr($buffer, 193, 9));      // format RSF-A 2015
            
            //if (get_numrss($BUF_record["no_rss"]) == 0) {
                // $BUF_record["no_rss"] = trim($current_rsfa_index + 99000000000);
                $BUF_record["no_rss"] = '9' . str_pad(trim($current_rsfa_index), 8, '0', STR_PAD_LEFT);
            //}
            $BUF_record["ok"] = TRUE;       
            break;
        case "ACE2016" :
            $BUF_record["BUF_offsets"] = $rsf_ace_offsets_2016_A;
        
            $BUF_record["no_rss"] = 0;
            $BUF_record["sexe"] = trim(substr($buffer, 19, 1));
            $BUF_record["civilite"] = trim(substr($buffer, 20, 1));
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 21, 13));
            $BUF_record["cle_immatriculation_assure"] = trim(substr($buffer, 34, 2));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 36, 3));
            $BUF_record["no_facture"] = trim(substr($buffer, 39, 9));
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 39, 9));
            $BUF_record["nature_operation"] = trim(substr($buffer, 49, 1));
            $BUF_record["nature_assurance"] = trim(substr($buffer, 50, 2));
            $BUF_record["justificatif_exo"] = trim(substr($buffer, 52, 1));
            $BUF_record["code_pec"] = trim(substr($buffer, 53, 1));
            $BUF_record["motif_non_facturation"] = trim(substr($buffer, 54, 1));
            $BUF_record["grand_regime"] = trim(substr($buffer, 55, 2));
            $BUF_record["date_naissance"] = trim(substr($buffer, 57, 8));
            $BUF_record["rang_naissance"] = trim(substr($buffer, 65, 1));
            $BUF_record["date_entree"] = trim(substr($buffer, 66, 8));
            $BUF_record["date_sortie"] = trim(substr($buffer, 74, 8));
            $BUF_record["code_postal"] = trim(substr($buffer, 82, 5));
            $BUF_record["base_remboursement_c"] = trim(substr($buffer, 87, 8));
            $BUF_record["total_remboursable_amo"] = trim(substr($buffer, 95, 8));
            $BUF_record["total_honoraires_factures"] = trim(substr($buffer, 103, 8));
            $BUF_record["total_honoraires_remboursable"] = trim(substr($buffer, 111, 8));
            $BUF_record["total_assure_avant_oc"] = trim(substr($buffer, 119, 8));
            $BUF_record["total_remboursable_oc_ph"] = trim(substr($buffer, 127, 8));
            $BUF_record["total_remboursable_oc_honoraires"] = trim(substr($buffer, 135, 8));
            $BUF_record["total_facture_ph"] = trim(substr($buffer, 143, 8));
            $BUF_record["pat_benef_cmu"] = trim(substr($buffer, 151, 1));
            $BUF_record["valorise_fides"] = trim(substr($buffer, 152, 1));
            $BUF_record["code_gestion"] = trim(substr($buffer, 153, 2));
            $BUF_record["no_organisme_complementaire"] = trim(substr($buffer, 154, 10));        // format RSF-A 2015
            $BUF_record["no_at_date_adc"] = trim(substr($buffer, 174, 9));      // format RSF-A 2015
            
            //if (get_numrss($BUF_record["no_rss"]) == 0) {
                // $BUF_record["no_rss"] = trim($current_rsfa_index + 99000000000);
                $BUF_record["no_rss"] = '9' . str_pad(trim($current_rsfa_index), 8, '0', STR_PAD_LEFT);
            //}
            $BUF_record["ok"] = TRUE;       
            break;
        case "ACE2015" :
            $BUF_record["BUF_offsets"] = $rsf_ace_offsets_2015_A;
        
            $BUF_record["no_rss"] = 0;
            $BUF_record["sexe"] = trim(substr($buffer, 10, 1));
            $BUF_record["civilite"] = trim(substr($buffer, 11, 1));
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 12, 13));
            $BUF_record["cle_immatriculation_assure"] = trim(substr($buffer, 25, 2));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 27, 3));
            $BUF_record["no_facture"] = trim(substr($buffer, 30, 9));
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 30, 9));
            $BUF_record["nature_operation"] = trim(substr($buffer, 40, 1));
            $BUF_record["nature_assurance"] = trim(substr($buffer, 41, 2));
            $BUF_record["justificatif_exo"] = trim(substr($buffer, 43, 1));
            $BUF_record["code_pec"] = trim(substr($buffer, 44, 1));
            $BUF_record["motif_non_facturation"] = trim(substr($buffer, 45, 1));
            $BUF_record["grand_regime"] = trim(substr($buffer, 46, 2));
            $BUF_record["date_naissance"] = trim(substr($buffer, 48, 8));
            $BUF_record["rang_naissance"] = trim(substr($buffer, 56, 1));
            $BUF_record["date_entree"] = trim(substr($buffer, 57, 8));
            $BUF_record["date_sortie"] = trim(substr($buffer, 65, 8));
            $BUF_record["code_postal"] = trim(substr($buffer, 73, 5));
            $BUF_record["base_remboursement_c"] = trim(substr($buffer, 78, 8));
            $BUF_record["total_remboursable_amo"] = trim(substr($buffer, 86, 8));
            $BUF_record["total_honoraires_factures"] = trim(substr($buffer, 94, 8));
            $BUF_record["total_honoraires_remboursable"] = trim(substr($buffer, 102, 8));
            $BUF_record["total_assure_avant_oc"] = trim(substr($buffer, 110, 8));
            $BUF_record["total_remboursable_oc_ph"] = trim(substr($buffer, 118, 8));
            $BUF_record["total_remboursable_oc_honoraires"] = trim(substr($buffer, 126, 8));
            $BUF_record["total_facture_ph"] = trim(substr($buffer, 134, 8));
            $BUF_record["pat_benef_cmu"] = trim(substr($buffer, 142, 1));
            $BUF_record["valorise_fides"] = trim(substr($buffer, 143, 1));
            $BUF_record["code_gestion"] = trim(substr($buffer, 144, 2));
            $BUF_record["no_organisme_complementaire"] = trim(substr($buffer, 145, 10));        // format RSF-A 2015
            $BUF_record["no_at_date_adc"] = trim(substr($buffer, 165, 9));      // format RSF-A 2015
            
            //if (get_numrss($BUF_record["no_rss"]) == 0) {
                // $BUF_record["no_rss"] = trim($current_rsfa_index + 99000000000);
                $BUF_record["no_rss"] = '9' . str_pad(trim($current_rsfa_index), 8, '0', STR_PAD_LEFT);
            //}
            $BUF_record["ok"] = TRUE;       
            break;
        case "ACE2009" :
            $BUF_record["BUF_offsets"] = $rsf_ace_offsets_2009_A;
        
            $BUF_record["no_rss"] = 0;
            $BUF_record["sexe"] = trim(substr($buffer, 10, 1));
            $BUF_record["civilite"] = trim(substr($buffer, 11, 1));
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 12, 13));
            $BUF_record["cle_immatriculation_assure"] = trim(substr($buffer, 25, 2));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 27, 3));
            $BUF_record["no_facture"] = trim(substr($buffer, 30, 9));
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 30, 9));
            $BUF_record["nature_operation"] = trim(substr($buffer, 40, 1));
            $BUF_record["nature_assurance"] = trim(substr($buffer, 41, 2));
            $BUF_record["justificatif_exo"] = trim(substr($buffer, 43, 1));
            $BUF_record["code_pec"] = trim(substr($buffer, 44, 1));
            $BUF_record["motif_non_facturation"] = trim(substr($buffer, 45, 1));
            $BUF_record["grand_regime"] = trim(substr($buffer, 46, 2));
            $BUF_record["date_naissance"] = trim(substr($buffer, 48, 8));
            $BUF_record["rang_naissance"] = trim(substr($buffer, 56, 1));
            $BUF_record["date_entree"] = trim(substr($buffer, 57, 8));
            $BUF_record["date_sortie"] = trim(substr($buffer, 65, 8));
            $BUF_record["code_postal"] = trim(substr($buffer, 73, 5));
            $BUF_record["base_remboursement_c"] = trim(substr($buffer, 78, 8));
            $BUF_record["total_remboursable_amo"] = trim(substr($buffer, 86, 8));
            $BUF_record["total_honoraires_factures"] = trim(substr($buffer, 94, 8));
            $BUF_record["total_honoraires_remboursable"] = trim(substr($buffer, 102, 8));
            $BUF_record["total_assure_avant_oc"] = trim(substr($buffer, 110, 8));
            $BUF_record["total_remboursable_oc_ph"] = trim(substr($buffer, 118, 8));
            $BUF_record["total_remboursable_oc_honoraires"] = trim(substr($buffer, 126, 8));
            $BUF_record["total_facture_ph"] = trim(substr($buffer, 134, 8));
            $BUF_record["pat_benef_cmu"] = trim(substr($buffer, 142, 1));
            $BUF_record["valorise_fides"] = trim(substr($buffer, 143, 1));
            $BUF_record["code_gestion"] = trim(substr($buffer, 144, 2));    // format RSF-ACE 2014
            
            //if (get_numrss($BUF_record["no_rss"]) == 0) {
                // $BUF_record["no_rss"] = trim($current_rsfa_index + 99000000000);
                $BUF_record["no_rss"] = '9' . str_pad(trim($current_rsfa_index), 8, '0', STR_PAD_LEFT);
            //}
            $BUF_record["ok"] = TRUE;       
            break;
        case "ACE2008" :
            $BUF_record["BUF_offsets"] = $rsf_ace_offsets_2008_A;
        
            $BUF_record["no_rss"] = 0;
            $BUF_record["sexe"] = trim(substr($buffer, 10, 1));
            $BUF_record["civilite"] = trim(substr($buffer, 11, 1));
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 12, 13));
            $BUF_record["cle_immatriculation_assure"] = trim(substr($buffer, 25, 2));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 27, 3));
            $BUF_record["no_facture"] = trim(substr($buffer, 30, 9));
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 30, 9));
            $BUF_record["nature_operation"] = trim(substr($buffer, 40, 1));
            $BUF_record["nature_assurance"] = trim(substr($buffer, 41, 2));
            $BUF_record["justificatif_exo"] = trim(substr($buffer, 43, 1));
            $BUF_record["code_pec"] = trim(substr($buffer, 44, 1));
            $BUF_record["grand_regime"] = trim(substr($buffer, 45, 2));
            $BUF_record["date_naissance"] = trim(substr($buffer, 47, 8));
            $BUF_record["rang_naissance"] = trim(substr($buffer, 55, 1));
            $BUF_record["date_entree"] = trim(substr($buffer, 56, 8));
            $BUF_record["date_sortie"] = trim(substr($buffer, 64, 8));
            $BUF_record["base_remboursement_c"] = trim(substr($buffer, 72, 8));
            $BUF_record["total_remboursable_amo"] = trim(substr($buffer, 80, 8));
            $BUF_record["total_honoraires_factures"] = trim(substr($buffer, 88, 8));
            $BUF_record["total_honoraires_remboursable"] = trim(substr($buffer, 96, 8));
            $BUF_record["total_assure_avant_oc"] = trim(substr($buffer, 104, 8));
            $BUF_record["total_remboursable_oc_ph"] = trim(substr($buffer, 112, 8));
            $BUF_record["total_remboursable_oc_honoraires"] = trim(substr($buffer, 120, 8));
            $BUF_record["total_facture_ph"] = trim(substr($buffer, 128, 8));
            
            //if (get_numrss($BUF_record["no_rss"]) == 0) {
                // $BUF_record["no_rss"] = trim($current_rsfa_index + 99000000000);
                $BUF_record["no_rss"] = '9' . str_pad(trim($current_rsfa_index), 8, '0', STR_PAD_LEFT);
            //}
            $BUF_record["ok"] = TRUE;       
            break;
        case "ACE2007" :
            $BUF_record["BUF_offsets"] = $rsf_ace_offsets_2007_A;
        
            $BUF_record["no_rss"] = 0;
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 10, 9));
            $BUF_record["sexe"] = trim(substr($buffer, 19, 1));
            $BUF_record["civilite"] = trim(substr($buffer, 19, 1));
            if ($BUF_record["sexe"] != "1" && $BUF_record["sexe"] != "2" && $BUF_record["sexe"] != "3") {
                $BUF_record["sexe"] = "1";
                $BUF_record["civilite"] = "1";
            }
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 19, 13));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 32, 3));
            $BUF_record["nature_operation"] = trim(substr($buffer, 35, 1));
            $BUF_record["nature_assurance"] = trim(substr($buffer, 36, 2));
            $BUF_record["justificatif_exo"] = trim(substr($buffer, 38, 1));
            $BUF_record["code_pec"] = trim(substr($buffer, 39, 1));
            $BUF_record["no_facture"] = trim(substr($buffer, 40, 9));
            $BUF_record["grand_regime"] = trim(substr($buffer, 49, 2));
            $BUF_record["date_naissance"] = trim(substr($buffer, 51, 8));
            $BUF_record["rang_naissance"] = trim(substr($buffer, 59, 1));
            $BUF_record["date_entree"] = trim(substr($buffer, 60, 8));
            $BUF_record["date_sortie"] = trim(substr($buffer, 68, 8));
            
            $BUF_record["base_remboursement_c"] = trim(substr($buffer, 76, 8));
            $BUF_record["total_remboursable_amo"] = trim(substr($buffer, 84, 8));
            $BUF_record["total_honoraires_factures"] = trim(substr($buffer, 92, 8));
            $BUF_record["total_honoraires_remboursable"] = trim(substr($buffer, 100, 8));
            $BUF_record["total_assure_avant_oc"] = trim(substr($buffer, 108, 8));
            $BUF_record["total_remboursable_oc_ph"] = trim(substr($buffer, 116, 8));
            $BUF_record["total_remboursable_oc_honoraires"] = trim(substr($buffer, 124, 8));
            $BUF_record["total_facture_ph"] = trim(substr($buffer, 132, 8));
            
            //if (get_numrss($BUF_record["no_rss"]) == 0) {
                // $BUF_record["no_rss"] = trim($current_rsfa_index + 99000000000);
                $BUF_record["no_rss"] = '9' . str_pad(trim($current_rsfa_index), 8, '0', STR_PAD_LEFT);
            //}
            $BUF_record["ok"] = TRUE;       
            break;
        case "ACE2007I" :
            $BUF_record["BUF_offsets"] = $rsf_ace_offsets_2007_A;
        
            $BUF_record["no_rss"] = 0;
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 10, 9));
            $BUF_record["sexe"] = trim(substr($buffer, 19, 1));
            $BUF_record["civilite"] = trim(substr($buffer, 20, 1));
            if ($BUF_record["sexe"] != "1" && $BUF_record["sexe"] != "2" && $BUF_record["sexe"] != "3") {
                $BUF_record["sexe"] = "1";
                $BUF_record["civilite"] = "1";
            }
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 21, 13));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 34, 3));
            $BUF_record["nature_operation"] = trim(substr($buffer, 37, 1));
            $BUF_record["nature_assurance"] = trim(substr($buffer, 38, 2));
            $BUF_record["justificatif_exo"] = trim(substr($buffer, 40, 1));
            $BUF_record["code_pec"] = trim(substr($buffer, 41, 1));
            $BUF_record["no_facture"] = trim(substr($buffer, 42, 9));
            $BUF_record["grand_regime"] = trim(substr($buffer, 51, 2));
            $BUF_record["date_naissance"] = trim(substr($buffer, 53, 8));
            $BUF_record["rang_naissance"] = trim(substr($buffer, 61, 1));
            $BUF_record["date_entree"] = trim(substr($buffer, 62, 8));
            $BUF_record["date_sortie"] = trim(substr($buffer, 70, 8));
            
            $BUF_record["base_remboursement_c"] = trim(substr($buffer, 76, 8));
            $BUF_record["total_remboursable_amo"] = trim(substr($buffer, 84, 8));
            $BUF_record["total_honoraires_factures"] = trim(substr($buffer, 92, 8));
            $BUF_record["total_honoraires_remboursable"] = trim(substr($buffer, 100, 8));
            $BUF_record["total_assure_avant_oc"] = trim(substr($buffer, 108, 8));
            $BUF_record["total_remboursable_oc_ph"] = trim(substr($buffer, 116, 8));
            $BUF_record["total_remboursable_oc_honoraires"] = trim(substr($buffer, 124, 8));
            $BUF_record["total_facture_ph"] = trim(substr($buffer, 132, 8));

            //if (get_numrss($BUF_record["no_rss"]) == 0) {
                // $BUF_record["no_rss"] = trim($current_rsfa_index + 99000000000);
                $BUF_record["no_rss"] = '9' . str_pad(trim($current_rsfa_index), 8, '0', STR_PAD_LEFT);
            //}
            $BUF_record["ok"] = TRUE;       
            break;
        default :
            // nothing to do
        }
        // remplacement de l'immatriculation de l'assuré si l'immatriculation individuelle est renseignée
        if ($BUF_record["immatriculation_indiv"] != "" && floatval($BUF_record["immatriculation_indiv"]) != 0) {
            $BUF_record["immatriculation_assure"] = $BUF_record["immatriculation_indiv"];
            $BUF_record["cle_immatriculation_assure"] = $BUF_record["cle_immatriculation_indiv"];
        }
        
        
        //if($BUF_record["date_paiement_amo"] === '44210000') {
        //    echo "\r\n" . date("d/m/Y H:i:s") . "\t" . "DEBUG" . "\t" . "DATE PAIEMENT AMO l. 23140 : " . $BUF_record["date_paiement_amo"] ;
        //}
        
        
        // if ($BUF_record["grand_regime"] == "XX") {
            // $BUF_record["grand_regime"] = "01";
        // }
        // if ($BUF_record["grand_regime"] == "DI") {
            // $BUF_record["grand_regime"] = "01";
        // }
        if ($BUF_record["sexe"] == "") {
            $BUF_record["sexe"] = "1";
        }
        
        $rsf_last_RSS = $BUF_record["no_rss"];
        
    }
    
    // RSF B Prestations hospitalières
    if ($BUF_record["type_enregistrement"] == "B" && $qB == TRUE) {
    
        if ($ENV_TYPEETS == "1") {
            $BUF_130 = trim(substr($buffer, 130, 100));
            if ($buf_len > 180 ) {
                $BUF_version = "2017";
            }
            else if ($BUF_130 == "") {
                $BUF_version = "2006";
            }
            else {
                $BUF_version = "2008";
            }
        }
        else {
            $BUF_115 = trim(substr($buffer, 115, 100)); //Format de mars 2016
            
            if ($buf_len > 150 ) {
                $BUF_version = "ACE2017";
            }
            else if ($BUF_115 != "") {
                    $BUF_version = "ACE2016";
            }
            else {
                    $BUF_version = "ACE2008";
            }   
        }

        $BUF_record["finess"] = trim(substr($buffer, 1, 9));
        $BUF_record["no_rss"] = "";
        
        switch ($BUF_version) {
        case "2017" :
            $BUF_record["BUF_offsets"] = $rsf_offsets_2017_B;
            
            $BUF_record["no_rss"] = trim(substr($buffer, 19, 20));
            $BUF_record["sexe"] = trim(substr($buffer, 39, 1));
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 39, 13));
            $BUF_record["cle_immatriculation_assure"] = trim(substr($buffer, 52, 2));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 54, 3));
            $BUF_record["no_facture"] = trim(substr($buffer, 57, 9));
            $BUF_record["immatriculation_indiv"] = trim(substr($buffer, 66, 13));
            $BUF_record["cle_immatriculation_indiv"] = trim(substr($buffer, 79, 2));
            $BUF_record["mode_traitement"] = trim(substr($buffer, 81, 2));
            $BUF_record["discpline_prestation"] = trim(substr($buffer, 83, 3));
            $BUF_record["justificatif_exo"] = trim(substr($buffer, 86, 1));
            $BUF_record["date_debut"] = trim(substr($buffer, 89, 8));
            $BUF_record["date_fin"] = trim(substr($buffer, 97, 8));
            $BUF_record["code_acte"] = trim(substr($buffer, 105, 5));
            $BUF_record["nombre"] = trim(substr($buffer, 110, 3));
            $BUF_record["coefficient"] = trim(substr($buffer, 113, 5));
            $BUF_record["code_pec_fj"] = trim(substr($buffer, 118, 1));
            $BUF_record["coefficient_mco"] = trim(substr($buffer, 119, 5));
            $BUF_record["prix_unitaire"] = trim(substr($buffer, 126, 7));
            $BUF_record["base_remboursement"] = trim(substr($buffer, 133, 8));
            $BUF_record["taux"] = trim(substr($buffer, 141, 3));
            $BUF_record["montant_remboursable"] = trim(substr($buffer, 144, 8));
            $BUF_record["montant_total_depense"] = trim(substr($buffer, 152, 8));
            $BUF_record["montant_remboursable_oc"] = trim(substr($buffer, 160, 7));
            $BUF_record["no_ghs"] = trim(substr($buffer, 167, 4));
            $BUF_record["montant_remboursé_noemie"] = trim(substr($buffer, 171, 8));
            $BUF_record["nature_noemie"] = trim(substr($buffer, 179, 3));
            if (get_numrss($BUF_record["no_rss"]) == 0) {
                $BUF_record["no_rss"] = $rsf_last_RSS;
            }
            $BUF_record["ok"] = TRUE;
            break;
        case "2008" :
            $BUF_record["BUF_offsets"] = $rsf_offsets_2008_B;
            
            $BUF_record["no_rss"] = trim(substr($buffer, 10, 20));
            $BUF_record["sexe"] = trim(substr($buffer, 30, 1));
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 32, 13));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 45, 3));
            $BUF_record["no_facture"] = trim(substr($buffer, 48, 9));
            $BUF_record["immatriculation_indiv"] = "";
            $BUF_record["cle_immatriculation_indiv"] = "";
            $BUF_record["mode_traitement"] = trim(substr($buffer, 57, 2));
            $BUF_record["discpline_prestation"] = trim(substr($buffer, 59, 3));
            $BUF_record["date_debut"] = trim(substr($buffer, 62, 8));
            $BUF_record["date_fin"] = trim(substr($buffer, 70, 8));
            $BUF_record["code_acte"] = trim(substr($buffer, 78, 5));
            $BUF_record["nombre"] = trim(substr($buffer, 83, 3));
            $BUF_record["justificatif_exo"] = trim(substr($buffer, 86, 1));
            $BUF_record["coefficient"] = trim(substr($buffer, 87, 5));
            $BUF_record["code_pec_fj"] = trim(substr($buffer, 92, 1));
            $BUF_record["coefficient_mco"] = trim(substr($buffer, 93, 5));
            $BUF_record["prix_unitaire"] = trim(substr($buffer, 98, 7));
            $BUF_record["base_remboursement"] = trim(substr($buffer, 105, 8));
            $BUF_record["taux"] = trim(substr($buffer, 113, 3));
            $BUF_record["montant_remboursable"] = trim(substr($buffer, 116, 8));
            $BUF_record["montant_total_depense"] = trim(substr($buffer, 124, 8));
            $BUF_record["montant_remboursable_oc"] = trim(substr($buffer, 132, 7));
            $BUF_record["no_ghs"] = trim(substr($buffer, 139, 4));
            $BUF_record["montant_remboursé_noemie"] = trim(substr($buffer, 143, 8));
            $BUF_record["nature_noemie"] = trim(substr($buffer, 151, 3));
            if (get_numrss($BUF_record["no_rss"]) == 0) {
                $BUF_record["no_rss"] = $rsf_last_RSS;
            }
            $BUF_record["ok"] = TRUE;
            break;
        case "2006" :
            $BUF_record["BUF_offsets"] = $rsf_offsets_2006_B;
            
            $BUF_record["no_rss"] = trim(substr($buffer, 10, 7));
            $BUF_record["sexe"] = "";
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 17, 13));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 30, 3));
            $BUF_record["no_facture"] = "";
            $BUF_record["immatriculation_indiv"] = "";
            $BUF_record["cle_immatriculation_indiv"] = "";
            $BUF_record["mode_traitement"] = trim(substr($buffer, 33, 2));
            $BUF_record["discpline_prestation"] = trim(substr($buffer, 35, 3));
            $BUF_record["date_debut"] = trim(substr($buffer, 38, 8));
            $BUF_record["date_fin"] = trim(substr($buffer, 46, 8));
            $BUF_record["code_acte"] = trim(substr($buffer, 54, 5));
            $BUF_record["nombre"] = trim(substr($buffer, 59, 3));
            $BUF_record["justificatif_exo"] = trim(substr($buffer, 62, 1));
            $BUF_record["coefficient"] = trim(substr($buffer, 63, 5));
            $BUF_record["code_pec_fj"] = trim(substr($buffer, 68, 1));
            $BUF_record["coefficient_mco"] = trim(substr($buffer, 69, 5));
            $BUF_record["prix_unitaire"] = trim(substr($buffer, 74, 7));
            $BUF_record["base_remboursement"] = trim(substr($buffer, 81, 8));
            $BUF_record["taux"] = trim(substr($buffer, 89, 3));
            $BUF_record["montant_remboursable"] = trim(substr($buffer, 92, 8));
            $BUF_record["montant_total_depense"] = trim(substr($buffer, 100, 8));
            $BUF_record["montant_remboursable_oc"] = trim(substr($buffer, 108, 7));
            $BUF_record["no_ghs"] = trim(substr($buffer, 115, 4));
            $BUF_record["montant_remboursé_noemie"] = trim(substr($buffer, 119, 8));
            $BUF_record["nature_noemie"] = trim(substr($buffer, 127, 3));
            if (get_numrss($BUF_record["no_rss"]) == 0) {
                $BUF_record["no_rss"] = $rsf_last_RSS;
            }
            $BUF_record["ok"] = TRUE;
            break;
        case "ACE2017" :
            $BUF_record["BUF_offsets"] = $rsf_ace_offsets_2017_B;
            
            $BUF_record["no_rss"] = 0;
            $BUF_record["sexe"] = "";
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 19, 13));
            $BUF_record["cle_immatriculation_assure"] = trim(substr($buffer, 32, 2));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 34, 3));
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 37, 9));
            $BUF_record["immatriculation_indiv"] = trim(substr($buffer, 46, 13));
            $BUF_record["cle_immatriculation_indiv"] = trim(substr($buffer, 59, 2));
            $BUF_record["no_facture"] = trim(substr($buffer, 37, 9));
            $BUF_record["mode_traitement"] = trim(substr($buffer, 61, 2));
            $BUF_record["discpline_prestation"] = trim(substr($buffer, 63, 3));
            $BUF_record["justificatif_exo"] = trim(substr($buffer, 66, 1));
            $BUF_record["specialite_executant"] = trim(substr($buffer, 67, 1));
            $BUF_record["date_debut"] = trim(substr($buffer, 69, 8));
            $BUF_record["date_fin"] = trim(substr($buffer, 69, 8));
            $BUF_record["code_acte"] = trim(substr($buffer, 77, 5));
            $BUF_record["nombre"] = trim(substr($buffer, 82, 3));
            $BUF_record["coefficient"] = trim(substr($buffer, 85, 6));
            $BUF_record["code_pec_fj"] = trim(substr($buffer, 91, 1));
            $BUF_record["coefficient_mco"] = trim(substr($buffer, 92, 5));
            $BUF_record["prix_unitaire"] = trim(substr($buffer, 99, 7));
            $BUF_record["base_remboursement"] = trim(substr($buffer, 106, 8));
            $BUF_record["taux"] = trim(substr($buffer, 114, 3));
            $BUF_record["montant_remboursable"] = trim(substr($buffer, 117, 8));
            $BUF_record["montant_total_depense"] = trim(substr($buffer, 125, 8));
            $BUF_record["montant_remboursable_oc"] = trim(substr($buffer, 133, 7));
            $BUF_record["no_ghs"] = "0000";
            $BUF_record["montant_remboursé_noemie"] = "00000000";
            $BUF_record["nature_noemie"] = "";

            $BUF_record["no_rss"] = $rsf_last_RSS;

            $BUF_record["ok"] = TRUE;
            break;
        case "ACE2016" :
            $BUF_record["BUF_offsets"] = $rsf_ace_offsets_2016_B;
            
            $BUF_record["no_rss"] = 0;
            $BUF_record["sexe"] = "1";
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 19, 13));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 34, 3));
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 37, 9));
            $BUF_record["immatriculation_indiv"] = "";
            $BUF_record["cle_immatriculation_indiv"] = "";
            $BUF_record["no_facture"] = trim(substr($buffer, 37, 9));
            $BUF_record["mode_traitement"] = trim(substr($buffer, 46, 2));
            $BUF_record["discpline_prestation"] = trim(substr($buffer, 48, 3));
            $BUF_record["justificatif_exo"] = trim(substr($buffer, 51, 1));
            $BUF_record["date_debut"] = trim(substr($buffer, 54, 8));
            $BUF_record["date_fin"] = trim(substr($buffer, 54, 8));
            $BUF_record["code_acte"] = trim(substr($buffer, 62, 5));
            $BUF_record["nombre"] = trim(substr($buffer, 67, 3));
            $BUF_record["coefficient"] = trim(substr($buffer, 70, 6));
            $BUF_record["code_pec_fj"] = "";
            $BUF_record["coefficient_mco"] = trim(substr($buffer, 119, 5));
            $BUF_record["prix_unitaire"] = trim(substr($buffer, 78, 7));
            $BUF_record["base_remboursement"] = trim(substr($buffer, 85, 8));
            $BUF_record["taux"] = trim(substr($buffer, 93, 3));
            $BUF_record["montant_remboursable"] = trim(substr($buffer, 96, 8));
            $BUF_record["montant_total_depense"] = trim(substr($buffer, 104, 8));
            $BUF_record["montant_remboursable_oc"] = trim(substr($buffer, 112, 7));
            $BUF_record["no_ghs"] = "0000";
            $BUF_record["montant_remboursé_noemie"] = "00000000";
            $BUF_record["nature_noemie"] = "";

            $BUF_record["no_rss"] = $rsf_last_RSS;

            $BUF_record["ok"] = TRUE;
            break;
        case "ACE2008" :
            $BUF_record["BUF_offsets"] = $rsf_ace_offsets_2008_B;
            
            $BUF_record["no_rss"] = 0;
            $BUF_record["sexe"] = "1";
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 10, 13));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 25, 3));
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 28, 9));
            $BUF_record["no_facture"] = trim(substr($buffer, 28, 9));
            $BUF_record["immatriculation_indiv"] = "";
            $BUF_record["cle_immatriculation_indiv"] = "";
            $BUF_record["mode_traitement"] = trim(substr($buffer, 37, 2));
            $BUF_record["discpline_prestation"] = trim(substr($buffer, 39, 3));
            $BUF_record["justificatif_exo"] = trim(substr($buffer, 42, 1));
            $BUF_record["date_debut"] = trim(substr($buffer, 45, 8));
            $BUF_record["date_fin"] = trim(substr($buffer, 45, 8));
            $BUF_record["code_acte"] = trim(substr($buffer, 53, 5));
            $BUF_record["nombre"] = trim(substr($buffer, 58, 3));
            $BUF_record["coefficient"] = trim(substr($buffer, 61, 6));
            $BUF_record["code_pec_fj"] = "";
            $BUF_record["prix_unitaire"] = trim(substr($buffer, 69, 7));
            $BUF_record["base_remboursement"] = trim(substr($buffer, 76, 8));
            $BUF_record["taux"] = trim(substr($buffer, 84, 3));
            $BUF_record["montant_remboursable"] = trim(substr($buffer, 87, 8));
            $BUF_record["montant_total_depense"] = trim(substr($buffer, 95, 8));
            $BUF_record["montant_remboursable_oc"] = trim(substr($buffer, 103, 7));
            $BUF_record["coefficient_mco"] = trim(substr($buffer, 110, 5)); // RSF_ACE B 2014
            $BUF_record["no_ghs"] = "0000";
            $BUF_record["montant_remboursé_noemie"] = "00000000";
            $BUF_record["nature_noemie"] = "";

            $BUF_record["no_rss"] = $rsf_last_RSS;

            $BUF_record["ok"] = TRUE;
            break;
        default :
            // nothing to do
        }
        
        if (trim($BUF_record["date_fin"]) == "") {
            $BUF_record["date_fin"] = $BUF_record["date_debut"];
        }
        
    }
    
    // RSF C Honoraires
    if ($BUF_record["type_enregistrement"] == "C" && $qB == TRUE) {
    
        // Pour le privé, on ne traite les RSF_C que si l'option "Considérer les FSD comme des prestations cliniques et non honoraires" est activée dans les paramètres systèmes de l'application
        // On les considère alors comme des type B, le CA des honoraire est récupéré par la clinique et non pas par les médecins
        if ($ENV_TYPEETS == "1") {
            
            if($ENV_OPTPMSI_FSD_B == "1") {
                
                $BUF_130 = trim(substr($buffer, 130, 100));
                
                if ($buf_len > 165 ) {
                    $BUF_version = "2017";
                    $BUF_record["code_acte"] = trim(substr($buffer, 97, 5));
                }
                else if ($BUF_130 == "") {
                    $BUF_version = "2003";
                    $BUF_record["code_acte"] = trim(substr($buffer, 47, 5));
                }
                else {
                    $BUF_version = "2008";
                    $BUF_record["code_acte"] = trim(substr($buffer, 71, 5));
                }
                if ($BUF_record["code_acte"] == "FSD") {
                    switch ($BUF_version) {
                    case "2017" :
                        $BUF_record["finess"] = trim(substr($buffer, 1, 9));
                        $BUF_record["no_rss"] = trim(substr($buffer, 19, 20));
                        $BUF_record["immatriculation_assure"] = trim(substr($buffer, 39, 13));
                        $BUF_record["cle_immatriculation_assure"] = trim(substr($buffer, 52, 2));
                        $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 54, 3));
                        $BUF_record["no_facture"] = trim(substr($buffer, 57, 9));
                        $BUF_record["immatriculation_indiv"] = trim(substr($buffer, 66, 13));
                        $BUF_record["cle_immatriculation_indiv"] = trim(substr($buffer, 79, 2));
                        $BUF_record["mode_traitement"] = trim(substr($buffer, 81, 2));
                        $BUF_record["discpline_prestation"] = trim(substr($buffer, 83, 3));
                        $BUF_record["justificatif_exo"] = trim(substr($buffer, 86, 1));
                        $BUF_record["specialite_executant"] = trim(substr($buffer, 87, 2));
                        $BUF_record["date_debut"] = trim(substr($buffer, 89, 8));
                        $BUF_record["date_fin"] = trim(substr($buffer, 89, 8));
                        $BUF_record["code_acte"] = trim(substr($buffer, 97, 5));
                        $BUF_record["nombre"] = trim(substr($buffer, 102, 2));
                        $BUF_record["coefficient"] = trim(substr($buffer, 104, 6));
                        $BUF_record["coefficient_mco"] = "10000";
                        $BUF_record["denombrement"] = trim(substr($buffer, 110, 2));
                        $BUF_record["prix_unitaire"] = trim(substr($buffer, 112, 7));
                        $BUF_record["base_remboursement"] = trim(substr($buffer, 119, 7));
                        $BUF_record["taux"] = trim(substr($buffer, 126, 3));
                        $BUF_record["montant_remboursable"] = trim(substr($buffer, 129, 7));
                        $BUF_record["montant_total_depense"] = trim(substr($buffer, 136, 7));
                        $BUF_record["montant_remboursable_oc"] = trim(substr($buffer, 143, 6));
                        $BUF_record["montant_remboursé_noemie"] = trim(substr($buffer, 149, 8));
                        $BUF_record["nature_noemie"] = trim(substr($buffer, 157, 3));
                        $BUF_record["type_uf_consultation"] = "";       // RSF_ACE C 2014
                        if (get_numrss($BUF_record["no_rss"]) == 0) {
                            $BUF_record["no_rss"] = $rsf_last_RSS;
                        }
                        $BUF_record["ok"] = TRUE;
                        break;
                    case "2008" :
                        $BUF_record["finess"] = trim(substr($buffer, 1, 9));
                        $BUF_record["no_rss"] = trim(substr($buffer, 10, 20));
                        $BUF_record["immatriculation_assure"] = trim(substr($buffer, 30, 13));
                        $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 45, 3));
                        $BUF_record["no_facture"] = trim(substr($buffer, 48, 9));
                        $BUF_record["immatriculation_indiv"] = "";
                        $BUF_record["cle_immatriculation_indiv"] = "";
                        $BUF_record["mode_traitement"] = trim(substr($buffer, 57, 2));
                        $BUF_record["discpline_prestation"] = trim(substr($buffer, 59, 3));
                        $BUF_record["justificatif_exo"] = trim(substr($buffer, 62, 1));
                        $BUF_record["date_debut"] = trim(substr($buffer, 63, 8));
                        $BUF_record["date_fin"] = trim(substr($buffer, 63, 8));
                        $BUF_record["code_acte"] = trim(substr($buffer, 71, 5));
                        $BUF_record["nombre"] = trim(substr($buffer, 76, 2));
                        $BUF_record["coefficient"] = trim(substr($buffer, 78, 6));
                        $BUF_record["coefficient_mco"] = "10000";
                        $BUF_record["denombrement"] = trim(substr($buffer, 84, 2));
                        $BUF_record["prix_unitaire"] = trim(substr($buffer, 86, 7));
                        $BUF_record["base_remboursement"] = trim(substr($buffer, 93, 7));
                        $BUF_record["taux"] = trim(substr($buffer, 100, 3));
                        $BUF_record["montant_remboursable"] = trim(substr($buffer, 103, 7));
                        $BUF_record["montant_total_depense"] = trim(substr($buffer, 110, 7));
                        $BUF_record["montant_remboursable_oc"] = trim(substr($buffer, 117, 6));
                        $BUF_record["montant_remboursé_noemie"] = trim(substr($buffer, 123, 8));
                        $BUF_record["nature_noemie"] = trim(substr($buffer, 131, 3));
                        $BUF_record["type_uf_consultation"] = "";       // RSF_ACE C 2014
                        if (get_numrss($BUF_record["no_rss"]) == 0) {
                            $BUF_record["no_rss"] = $rsf_last_RSS;
                        }
                        $BUF_record["ok"] = TRUE;
                        break;
                    case "2003" :
                        $BUF_record["finess"] = trim(substr($buffer, 1, 9));
                        $BUF_record["no_rss"] = trim(substr($buffer, 10, 7));
                        $BUF_record["immatriculation_assure"] = trim(substr($buffer, 17, 13));
                        $BUF_record["immatriculation_indiv"] = "";
                        $BUF_record["cle_immatriculation_indiv"] = "";
                        $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 30, 3));
                        $BUF_record["mode_traitement"] = trim(substr($buffer, 33, 2));
                        $BUF_record["discpline_prestation"] = trim(substr($buffer, 35, 3));
                        $BUF_record["justificatif_exo"] = trim(substr($buffer, 38, 1));
                        $BUF_record["date_debut"] = trim(substr($buffer, 39, 8));
                        $BUF_record["date_fin"] = trim(substr($buffer, 39, 8));
                        $BUF_record["code_acte"] = trim(substr($buffer, 47, 5));
                        $BUF_record["nombre"] = trim(substr($buffer, 52, 2));
                        $BUF_record["coefficient"] = trim(substr($buffer, 54, 6));
                        $BUF_record["coefficient_mco"] = "10000";
                        $BUF_record["denombrement"] = trim(substr($buffer, 60, 2));
                        $BUF_record["prix_unitaire"] = trim(substr($buffer, 62, 7));
                        $BUF_record["base_remboursement"] = trim(substr($buffer, 69, 7));
                        $BUF_record["taux"] = trim(substr($buffer, 76, 3));
                        $BUF_record["montant_remboursable"] = trim(substr($buffer, 79, 7));
                        $BUF_record["montant_total_depense"] = trim(substr($buffer, 86, 7));
                        $BUF_record["montant_remboursable_oc"] = trim(substr($buffer, 93, 6));
                        $BUF_record["montant_remboursé_noemie"] = trim(substr($buffer, 99, 8));
                        $BUF_record["nature_noemie"] = trim(substr($buffer, 107, 3));
                        $BUF_record["type_uf_consultation"] = "";       // RSF_ACE C 2014
                        if (get_numrss($BUF_record["no_rss"]) == 0) {
                            $BUF_record["no_rss"] = $rsf_last_RSS;
                        }
                        $BUF_record["ok"] = TRUE;
                        break;
                    default :
                        // nothing to do
                    }
                }
                else {
                    $BUF_version = "NONE";
                }
            }
            else {
                $BUF_version = "NONE";
            }
        } else {

            $BUF_version = "NONE";
            $BUF_117 = trim(substr($buffer, 117, 100)); //Format de mars 2016
            

            if ($buf_len > 150 ) {
                $BUF_version = "ACE2017";
            }
            else if ($BUF_117 != "") {
                $BUF_version = "ACE2016";
            }               
            else {
                $BUF_49 = trim(substr($buffer, 49, 2));
                if ($BUF_49 == "20") {
                    $BUF_version = "ACE2008";
                } else {
                    $BUF_43 = trim(substr($buffer, 49, 2));
                    if ($BUF_43 == "20") {
                        $BUF_version = "ACE2007";
                    }
                }
            }

            
            $BUF_record["finess"] = trim(substr($buffer, 1, 9));
            $BUF_record["no_rss"] = "";
            
            if ($BUF_version == "ACE2017") {
                $BUF_record["BUF_offsets"] = $rsf_ace_offsets_2016_B;
                
                $BUF_record["no_rss"] = 0;
                $BUF_record["sexe"] = "1";
                $BUF_record["immatriculation_assure"] = trim(substr($buffer, 19, 13));
                $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 34, 3));
                $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 37, 9));
                $BUF_record["no_facture"] = trim(substr($buffer, 37, 9));
                $BUF_record["immatriculation_indiv"] = "";
                $BUF_record["cle_immatriculation_indiv"] = "";
                $BUF_record["mode_traitement"] = trim(substr($buffer, 61, 2));
                $BUF_record["discpline_prestation"] = trim(substr($buffer, 63, 3));
                $BUF_record["justificatif_exo"] = trim(substr($buffer, 66, 1));
                $BUF_record["specialite_exec"] = trim(substr($buffer, 67, 2));
                $BUF_record["date_debut"] = trim(substr($buffer, 69, 8));
                $BUF_record["date_fin"] = trim(substr($buffer, 69, 8));
                $BUF_record["code_acte"] = trim(substr($buffer, 77, 5));
                $BUF_record["nombre"] = trim(substr($buffer, 82, 3));
                $BUF_record["coefficient"] = trim(substr($buffer, 85, 6));
                $BUF_record["code_pec_fj"] = "";
                $BUF_record["prix_unitaire"] = trim(substr($buffer, 93, 7));
                $BUF_record["base_remboursement"] = trim(substr($buffer, 100, 8));
                $BUF_record["taux"] = trim(substr($buffer, 108, 3));
                $BUF_record["montant_remboursable"] = trim(substr($buffer, 111, 8));
                $BUF_record["montant_total_depense"] = trim(substr($buffer, 119, 8));
                $BUF_record["montant_remboursable_oc"] = trim(substr($buffer, 134, 7));
                $BUF_record["type_uf_consultation"] = trim(substr($buffer, 145, 2));    // RSF_ACE C 2014
                $BUF_record["coefficient_mco"] = trim(substr($buffer, 147, 5)); // RSF_ACE C 2014
                $BUF_record["no_ghs"] = "0000";
                $BUF_record["montant_remboursé_noemie"] = "00000000";
                $BUF_record["nature_noemie"] = "";

                $BUF_record["no_rss"] = $rsf_last_RSS;

                $BUF_record["ok"] = TRUE;
            }

            if ($BUF_version == "ACE2016") {
                $BUF_record["BUF_offsets"] = $rsf_ace_offsets_2016_B;
                
                $BUF_record["no_rss"] = 0;
                $BUF_record["sexe"] = "1";
                $BUF_record["immatriculation_assure"] = trim(substr($buffer, 19, 13));
                $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 34, 3));
                $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 37, 9));
                $BUF_record["no_facture"] = trim(substr($buffer, 37, 9));
                $BUF_record["immatriculation_indiv"] = "";
                $BUF_record["cle_immatriculation_indiv"] = "";
                $BUF_record["mode_traitement"] = trim(substr($buffer, 46, 2));
                $BUF_record["discpline_prestation"] = trim(substr($buffer, 48, 3));
                $BUF_record["justificatif_exo"] = trim(substr($buffer, 51, 1));
                $BUF_record["specialite_exec"] = trim(substr($buffer, 52, 2));
                $BUF_record["date_debut"] = trim(substr($buffer, 54, 8));
                $BUF_record["date_fin"] = trim(substr($buffer, 54, 8));
                $BUF_record["code_acte"] = trim(substr($buffer, 62, 5));
                $BUF_record["nombre"] = trim(substr($buffer, 67, 3));
                $BUF_record["coefficient"] = trim(substr($buffer, 70, 6));
                $BUF_record["code_pec_fj"] = "";
                $BUF_record["prix_unitaire"] = trim(substr($buffer, 78, 7));
                $BUF_record["base_remboursement"] = trim(substr($buffer, 85, 8));
                $BUF_record["taux"] = trim(substr($buffer, 93, 3));
                $BUF_record["montant_remboursable"] = trim(substr($buffer, 96, 8));
                $BUF_record["montant_total_depense"] = trim(substr($buffer, 104, 8));
                $BUF_record["montant_remboursable_oc"] = trim(substr($buffer, 112, 7));
                $BUF_record["type_uf_consultation"] = trim(substr($buffer, 119, 2));    // RSF_ACE C 2014
                $BUF_record["coefficient_mco"] = trim(substr($buffer, 121, 5)); // RSF_ACE C 2014
                $BUF_record["no_ghs"] = "0000";
                $BUF_record["montant_remboursé_noemie"] = "00000000";
                $BUF_record["nature_noemie"] = "";

                $BUF_record["no_rss"] = $rsf_last_RSS;

                $BUF_record["ok"] = TRUE;
            }

            if ($BUF_version == "ACE2008") {
                $BUF_record["BUF_offsets"] = $rsf_ace_offsets_2008_B;
                
                $BUF_record["no_rss"] = 0;
                $BUF_record["sexe"] = "1";
                $BUF_record["immatriculation_assure"] = trim(substr($buffer, 10, 13));
                $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 25, 3));
                $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 28, 9));
                $BUF_record["no_facture"] = trim(substr($buffer, 28, 9));
                $BUF_record["immatriculation_indiv"] = "";
                $BUF_record["cle_immatriculation_indiv"] = "";
                $BUF_record["mode_traitement"] = trim(substr($buffer, 37, 2));
                $BUF_record["discpline_prestation"] = trim(substr($buffer, 39, 3));
                $BUF_record["justificatif_exo"] = trim(substr($buffer, 42, 1));
                $BUF_record["specialite_exec"] = trim(substr($buffer, 43, 2));
                $BUF_record["date_debut"] = trim(substr($buffer, 45, 8));
                $BUF_record["date_fin"] = trim(substr($buffer, 45, 8));
                $BUF_record["code_acte"] = trim(substr($buffer, 53, 5));
                $BUF_record["nombre"] = trim(substr($buffer, 58, 3));
                $BUF_record["coefficient"] = trim(substr($buffer, 61, 6));
                $BUF_record["code_pec_fj"] = "";
                $BUF_record["prix_unitaire"] = trim(substr($buffer, 69, 7));
                $BUF_record["base_remboursement"] = trim(substr($buffer, 76, 8));
                $BUF_record["taux"] = trim(substr($buffer, 84, 3));
                $BUF_record["montant_remboursable"] = trim(substr($buffer, 87, 8));
                $BUF_record["montant_total_depense"] = trim(substr($buffer, 95, 8));
                $BUF_record["montant_remboursable_oc"] = trim(substr($buffer, 103, 7));
                $BUF_record["type_uf_consultation"] = trim(substr($buffer, 110, 2));    // RSF_ACE C 2014
                $BUF_record["coefficient_mco"] = trim(substr($buffer, 112, 5)); // RSF_ACE C 2014
                $BUF_record["no_ghs"] = "0000";
                $BUF_record["montant_remboursé_noemie"] = "00000000";
                $BUF_record["nature_noemie"] = "";

                $BUF_record["no_rss"] = $rsf_last_RSS;

                $BUF_record["ok"] = TRUE;
            }
            
            if ($BUF_version == "ACE2007") {
            
                $BUF_record["BUF_offsets"] = $rsf_ace_offsets_2008_B;
                
                $BUF_record["no_rss"] = 0;
                $BUF_record["sexe"] = trim(substr($buffer, 17, 1));
                if ($BUF_record["sexe"] != "1" && $BUF_record["sexe"] != "2" && $BUF_record["sexe"] != "3") {
                    $BUF_record["sexe"] = "1";
                }
                $BUF_record["immatriculation_assure"] = trim(substr($buffer, 17, 13));
                $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 30, 3));
                $BUF_record["no_sejour_administratif"] = "0";
                $BUF_record["no_facture"] = "0";
                $BUF_record["immatriculation_indiv"] = "";
                $BUF_record["cle_immatriculation_indiv"] = "";
                $BUF_record["mode_traitement"] = trim(substr($buffer, 33, 2));
                $BUF_record["discpline_prestation"] = trim(substr($buffer, 35, 3));
                $BUF_record["justificatif_exo"] = trim(substr($buffer, 38, 1));
                $BUF_record["date_debut"] = trim(substr($buffer, 39, 8));
                $BUF_record["date_fin"] = trim(substr($buffer, 39, 8));
                $BUF_record["code_acte"] = trim(substr($buffer, 47, 5));
                $BUF_record["nombre"] = trim(substr($buffer, 52, 2));
                $BUF_record["coefficient"] = trim(substr($buffer, 54, 6));
                $BUF_record["code_pec_fj"] = "";
                $BUF_record["coefficient_mco"] = "10000";
                $BUF_record["prix_unitaire"] = trim(substr($buffer, 62, 7));
                $BUF_record["base_remboursement"] = trim(substr($buffer, 69, 7));
                $BUF_record["taux"] = trim(substr($buffer, 76, 3));
                $BUF_record["montant_remboursable"] = trim(substr($buffer, 79, 7));
                $BUF_record["montant_total_depense"] = trim(substr($buffer, 86, 7));
                $BUF_record["montant_remboursable_oc"] = "0000000";
                $BUF_record["type_uf_consultation"] = "";       // RSF_ACE C 2014
                $BUF_record["no_ghs"] = "0000";
                $BUF_record["montant_remboursé_noemie"] = "0000000";
                $BUF_record["nature_noemie"] = "";

                $BUF_record["no_rss"] = $rsf_last_RSS;

                $BUF_record["ok"] = TRUE;
                
            }
        }
        
        if (trim($BUF_record["date_fin"]) == "") {
            $BUF_record["date_fin"] = $BUF_record["date_debut"];
        }
        
    }
    
    // RSF P (LPP)
    if ($BUF_record["type_enregistrement"] == "P" && $qP == TRUE) {
        $BUF_version_public = "";
        if ($ENV_TYPEETS == "1") { //PRIVE
            $BUF_100 = trim(substr($buffer, 100, 100));
            if ($buf_len > 135 ) {
                $BUF_version = "2017";
            }
            else if ($BUF_100 == "") {
                $BUF_version = "2006";
            }
            else {
                $BUF_version = "2008";
            }
        } 

        if ($ENV_TYPEETS !== "1") {  //PUBLIC ET ESPIC
            $BUF_version_public = "RSF_ACE_P_2023";
        }

        // Attention format 2008 sans la fin
        if ($BUF_version == "2006") {
            if (get_num(substr($buffer, 57, 4)) >= 2004 && get_num(substr($buffer, 57, 4)) <= 2010) {
                if (controle_check_date(trim(substr($buffer, 57, 8)),$erreur,$commentaire)) {
                    $BUF_version = "2008";
                }
            }
            if (get_num(substr($buffer, 61, 4)) >= 2004 && get_num(substr($buffer, 61, 4)) <= 2010) {
                if (controle_check_date(trim(substr($buffer, 57, 8)),$erreur,$commentaire)) {
                    $BUF_version = "2008";
                }
            }
        }

        $BUF_record["finess"] = trim(substr($buffer, 1, 9));
        $BUF_record["no_rss"] = "";
        
        switch ($BUF_version) {
        case "2017" :
            $BUF_record["BUF_offsets"] = $rsf_offsets_2017_P;
            
            $BUF_record["no_rss"] = trim(substr($buffer, 19, 20));
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 39, 13));
            $BUF_record["cle_immatriculation_assure"] = trim(substr($buffer, 52, 2));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 54, 3));
            $BUF_record["no_facture"] = trim(substr($buffer, 57, 9));
            $BUF_record["immatriculation_indiv"] = trim(substr($buffer, 66, 13));
            $BUF_record["cle_immatriculation_indiv"] = trim(substr($buffer, 79, 2));
            $BUF_record["date_debut"] = trim(substr($buffer, 81, 8));
            $BUF_record["code_lpp"] = trim(substr($buffer, 89, 13));
            $BUF_record["nombre"] = trim(substr($buffer, 102, 2));
            $BUF_record["prix_unitaire"] = trim(substr($buffer, 104, 7));
            $BUF_record["montant_facture"] = trim(substr($buffer, 111, 7));
            $BUF_record["code_lpp_2"] = "";
            $BUF_record["nombre_2"] = 0;
            $BUF_record["prix_unitaire_2"] = 0;
            $BUF_record["montant_facture_2"] = 0;
            if (get_numrss($BUF_record["no_rss"]) == 0) {
                $BUF_record["no_rss"] = $rsf_last_RSS;
            }
            $BUF_record["ok"] = TRUE;
            break;
        case "2008" :
            $BUF_record["BUF_offsets"] = $rsf_offsets_2008_P;
            
            $BUF_record["no_rss"] = trim(substr($buffer, 10, 20));
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 30, 13));
            $BUF_record["cle_immatriculation_assure"] = trim(substr($buffer, 43, 2));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 45, 3));
            $BUF_record["no_facture"] = trim(substr($buffer, 48, 9));
            $BUF_record["immatriculation_indiv"] = "";
            $BUF_record["cle_immatriculation_indiv"] = "";
            $BUF_record["date_debut"] = trim(substr($buffer, 57, 8));
            $BUF_record["code_lpp"] = trim(substr($buffer, 65, 13));
            $BUF_record["nombre"] = trim(substr($buffer, 78, 2));
            $BUF_record["prix_unitaire"] = trim(substr($buffer, 80, 7));
            $BUF_record["montant_facture"] = trim(substr($buffer, 87, 7));
            $BUF_record["code_lpp_2"] = "";
            $BUF_record["nombre_2"] = 0;
            $BUF_record["prix_unitaire_2"] = 0;
            $BUF_record["montant_facture_2"] = 0;
            if (get_numrss($BUF_record["no_rss"]) == 0) {
                $BUF_record["no_rss"] = $rsf_last_RSS;
            }
            $BUF_record["ok"] = TRUE;
            break;
        case "2006" :
            $BUF_record["BUF_offsets"] = $rsf_offsets_2006_P;
            
            $BUF_record["no_rss"] = trim(substr($buffer, 10, 7));
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 17, 13));
            $BUF_record["cle_immatriculation_assure"] = "";
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 30, 3));
            $BUF_record["no_facture"] = "";
            $BUF_record["immatriculation_indiv"] = "";
            $BUF_record["cle_immatriculation_indiv"] = "";
            $BUF_record["date_debut"] = trim(substr($buffer, 33, 8));
            $BUF_record["code_lpp"] = trim(substr($buffer, 41, 13));
            $BUF_record["nombre"] = trim(substr($buffer, 54, 2));
            $BUF_record["prix_unitaire"] = trim(substr($buffer, 56, 7));
            $BUF_record["montant_facture"] = trim(substr($buffer, 63, 7));
            $BUF_record["code_lpp_2"] = trim(substr($buffer, 70, 13));
            $BUF_record["nombre_2"] = trim(substr($buffer, 83, 2));
            $BUF_record["prix_unitaire_2"] = trim(substr($buffer, 85, 7));
            $BUF_record["montant_facture_2"] = trim(substr($buffer, 92, 7));
            if (get_numrss($BUF_record["no_rss"]) == 0) {
                $BUF_record["no_rss"] = $rsf_last_RSS;
            }
            $BUF_record["ok"] = TRUE;
            break;
        default :
            // nothing to do
        }

        if ($BUF_version_public === "RSF_ACE_P_2023"){
            //$BUF_record["BUF_offsets"] = $rsf_offsets_2017_P;// A FAIRE
            
            $BUF_record["no_rss"] = 0;
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 19, 13));
            $BUF_record["cle_immatriculation_assure"] = trim(substr($buffer, 32, 2));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 34, 3));
            $BUF_record["no_facture"] = trim(substr($buffer, 119, 9));
            if ($BUF_record["no_facture"] == "") {
                $BUF_record["no_facture"] = trim(substr($buffer, 37, 9));
            }
            $BUF_record["immatriculation_indiv"] = trim(substr($buffer, 46, 13));
            $BUF_record["cle_immatriculation_indiv"] = trim(substr($buffer, 59, 2));
            $BUF_record["date_debut"] = trim(substr($buffer, 61, 8));
            $BUF_record["code_lpp"] = trim(substr($buffer, 69, 13));
            $BUF_record["nombre"] = trim(substr($buffer, 82, 2));
            $BUF_record["prix_unitaire"] = trim(substr($buffer, 84, 7));
            $BUF_record["montant_facture"] = trim(substr($buffer, 91, 7));
            $BUF_record["code_lpp_2"] = "";
            $BUF_record["nombre_2"] = 0;
            $BUF_record["prix_unitaire_2"] = 0;
            $BUF_record["montant_facture_2"] = 0;
            if (get_numrss($BUF_record["no_rss"]) == 0) {
                $BUF_record["no_rss"] = $rsf_last_RSS;
            }
            $BUF_record["ok"] = TRUE;
        }
    }
    
    // RSF H (UCD)
    if ($BUF_record["type_enregistrement"] == "H" && $qH == TRUE) {
    
        if ($ENV_TYPEETS == "1") {
            $BUF_100 = trim(substr($buffer, 81, 100));
            if ($buf_len > 135 ) {
                $BUF_version = "2018";
            }
            else if ($buf_len > 130 ) {
                $BUF_version = "2017";
            }
            else if ($BUF_100 == "") {
                $BUF_version = "2006";
            }
            else {
                $BUF_version = "2008";
            }
        }
        
        // Initialisation variables
        $BUF_record["finess"] = trim(substr($buffer, 1, 9));
        $BUF_record["no_rss"] = "";
        $BUF_record["immatriculation_assure"] = "";
        $BUF_record["cle_immatriculation_assure"] = "";
        $BUF_record["rang_beneficiaire"] = "";
        $BUF_record["no_facture"] = "";
        $BUF_record["immatriculation_indiv"] = "";
        $BUF_record["cle_immatriculation_indiv"] = "";
        $BUF_record["date_debut"] = "";
        $BUF_record["code_ucd"] = "";
        $BUF_record["indication"] = "";
        $BUF_record["coefficient_fractionnement"] = "10000";
        $BUF_record["prix_unitaire_achat"] = "";
        $BUF_record["prix_unitaire_ecart_indemnisable"] = "0000000";
        $BUF_record["montant_ecart_indemnisable"] = "";
        $BUF_record["nombre"] = "";
        $BUF_record["montant_facture"] = "";
        
        switch ($BUF_version) {
        case "2018" :
            $BUF_record["BUF_offsets"] = $rsf_offsets_2017_H;
            
            $BUF_record["no_rss"] = trim(substr($buffer, 19, 20));
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 39, 13));
            $BUF_record["cle_immatriculation_assure"] = trim(substr($buffer, 52, 2));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 54, 3));
            $BUF_record["no_facture"] = trim(substr($buffer, 57, 9));
            $BUF_record["immatriculation_indiv"] = trim(substr($buffer, 66, 13));
            $BUF_record["cle_immatriculation_indiv"] = trim(substr($buffer, 79, 2));
            $BUF_record["date_debut"] = trim(substr($buffer, 81, 8));
            $BUF_record["code_ucd"] = trim(substr($buffer, 89, 7));
            $BUF_record["indication"] = trim(substr($buffer, 96, 7));
            $BUF_record["coefficient_fractionnement"] = trim(substr($buffer, 103, 5));
            $BUF_record["prix_unitaire_achat"] = trim(substr($buffer, 108, 7));
            $BUF_record["prix_unitaire_ecart_indemnisable"] = trim(substr($buffer, 115, 7));
            $BUF_record["montant_ecart_indemnisable"] = trim(substr($buffer, 122, 7));
            $BUF_record["nombre"] = trim(substr($buffer, 129, 3));
            $BUF_record["montant_facture"] = trim(substr($buffer, 132, 7));
            
            if (get_numrss($BUF_record["no_rss"]) == 0) {
                $BUF_record["no_rss"] = $rsf_last_RSS;
            }
            $BUF_record["ok"] = TRUE;
            break;
        case "2017" :
            $BUF_record["BUF_offsets"] = $rsf_offsets_2017_H;
            
            $BUF_record["no_rss"] = trim(substr($buffer, 19, 20));
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 39, 13));
            $BUF_record["cle_immatriculation_assure"] = trim(substr($buffer, 52, 2));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 54, 3));
            $BUF_record["no_facture"] = trim(substr($buffer, 57, 9));
            $BUF_record["immatriculation_indiv"] = trim(substr($buffer, 66, 13));
            $BUF_record["cle_immatriculation_indiv"] = trim(substr($buffer, 79, 2));
            $BUF_record["date_debut"] = trim(substr($buffer, 81, 8));
            $BUF_record["code_ucd"] = trim(substr($buffer, 89, 7));
            $BUF_record["coefficient_fractionnement"] = trim(substr($buffer, 96, 5));
            $BUF_record["prix_unitaire_achat"] = trim(substr($buffer, 101, 7));
            $BUF_record["prix_unitaire_ecart_indemnisable"] = trim(substr($buffer, 108, 7));
            $BUF_record["montant_ecart_indemnisable"] = trim(substr($buffer, 115, 7));
            $BUF_record["nombre"] = trim(substr($buffer, 122, 3));
            $BUF_record["montant_facture"] = trim(substr($buffer, 125, 7));
            
            if (get_numrss($BUF_record["no_rss"]) == 0) {
                $BUF_record["no_rss"] = $rsf_last_RSS;
            }
            $BUF_record["ok"] = TRUE;
            break;
        case "2008" :
            $BUF_record["BUF_offsets"] = $rsf_offsets_2008_P;
            
            $BUF_record["no_rss"] = trim(substr($buffer, 10, 20));
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 30, 13));
            $BUF_record["cle_immatriculation_assure"] = trim(substr($buffer, 43, 2));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 45, 3));
            $BUF_record["no_facture"] = trim(substr($buffer, 48, 9));
            $BUF_record["date_debut"] = trim(substr($buffer, 57, 8));
            $BUF_record["code_ucd"] = trim(substr($buffer, 65, 7));
            $BUF_record["coefficient_fractionnement"] = trim(substr($buffer, 72, 5));
            $BUF_record["prix_unitaire_achat"] = trim(substr($buffer, 77, 7));
            $BUF_record["prix_unitaire_ecart_indemnisable"] = trim(substr($buffer, 84, 7));
            $BUF_record["montant_ecart_indemnisable"] = trim(substr($buffer, 91, 7));
            $BUF_record["nombre"] = trim(substr($buffer, 98, 3));
            $BUF_record["montant_facture"] = trim(substr($buffer, 101, 7));
            
            if (get_numrss($BUF_record["no_rss"]) == 0) {
                $BUF_record["no_rss"] = $rsf_last_RSS;
            }
            $BUF_record["ok"] = TRUE;
            break;
        case "2006" :
            $BUF_record["BUF_offsets"] = $rsf_offsets_2006_P;
            
            $BUF_record["no_rss"] = trim(substr($buffer, 10, 7));
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 17, 13));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 30, 3));
            $BUF_record["date_debut"] = trim(substr($buffer, 33, 8));
            $BUF_record["code_ucd"] = trim(substr($buffer, 41, 7));
            $BUF_record["prix_unitaire_achat"] = trim(substr($buffer, 49, 7));
            $BUF_record["montant_ecart_indemnisable"] = trim(substr($buffer, 56, 7));
            $BUF_record["nombre"] = trim(substr($buffer, 70, 3));
            $BUF_record["montant_facture"] = trim(substr($buffer, 73, 7));
            
            if (get_numrss($BUF_record["no_rss"]) == 0) {
                $BUF_record["no_rss"] = $rsf_last_RSS;
            }
            $BUF_record["ok"] = TRUE;
            break;
        default :
            // nothing to do
        }
    }
    
    // actes CCAM
    if ($BUF_record["type_enregistrement"] == "M" && $qM == TRUE) {
    
        if ($ENV_TYPEETS == "1") {
            $BUF_46 = trim(substr($buffer, 46, 1));
            $BUF_70 = trim(substr($buffer, 70, 1));
            $BUF_76 = trim(substr($buffer, 76, 1));
            if ($buf_len > 145 ) {
                $BUF_version = "2017";
            }
            else if ($BUF_70 >= "A" && $BUF_70 <= "Z") {
                $BUF_version = "2008";
            }
            else {
                if ($BUF_76 >= "A" && $BUF_76 <= "Z" && trim($BUF_70) == "") {
                    $BUF_version = "2008B";
                }
                else {
                    if (trim($BUF_46) != "") {
                        $BUF_version = "2006";
                    }
                    else {
                        $BUF_version = "2006B";
                    }
                }
            }
        }
        else {
            $BUF_2016 = trim(substr($buffer, 51, 8)); //Format de mars 2016
            $BUF_2016_OK = "";
            if (substr($BUF_2016,4,2) == "20"  && substr($BUF_2016,2,2) < 13 && substr($BUF_2016,0,2) < 32 && is_numeric($BUF_2016)) {
                $BUF_2016_OK = "OK";
            }   
            $BUF_46 = trim(substr($buffer, 46, 2));

            if ($buf_len > 125) {
                $BUF_version = "ACE2017";
            } else if ($BUF_2016_OK == 'OK'  ) {
                $BUF_version = "ACE2016";
            }
            else{
                if (trim($BUF_46) == "20") {
                    $BUF_version = "ACE2008";
                }
                else {
                    $BUF_version = "ACE2007";
                }
            }   
        }

        $BUF_record["finess"] = trim(substr($buffer, 1, 9));
        $BUF_record["no_rss"] = "";
        
        switch ($BUF_version) {
        case "2017" :
            $BUF_record["BUF_offsets"] = $rsf_offsets_2017_M;
            
            $BUF_record["no_rss"] = trim(substr($buffer, 19, 20));
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 39, 13));
            $BUF_record["cle_immatriculation_assure"] = trim(substr($buffer, 52, 2));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 54, 3));
            $BUF_record["no_facture"] = trim(substr($buffer, 57, 9));
            $BUF_record["immatriculation_indiv"] = trim(substr($buffer, 66, 13));
            $BUF_record["cle_immatriculation_indiv"] = trim(substr($buffer, 79, 2));
            $BUF_record["mode_traitement"] = trim(substr($buffer, 81, 2));
            $BUF_record["discpline_prestation"] = trim(substr($buffer, 83, 3));
            $BUF_record["date_acte"] = trim(substr($buffer, 86, 8));
            $BUF_record["code_acte"] = trim(substr($buffer, 94, 7));
            $BUF_record["extension_ccam"] = trim(substr($buffer, 107, 1));
            $BUF_record["activite_ccam"] = trim(substr($buffer, 108, 1));
            $BUF_record["phase_ccam"] = trim(substr($buffer, 109, 1));
            $BUF_record["modificateur_ccam_1"] = trim(substr($buffer, 110, 1));
            $BUF_record["modificateur_ccam_2"] = trim(substr($buffer, 111, 1));
            $BUF_record["modificateur_ccam_3"] = trim(substr($buffer, 112, 1));
            $BUF_record["modificateur_ccam_4"] = trim(substr($buffer, 113, 1));
            $BUF_record["association_nonprevue_ccam"] = trim(substr($buffer, 114, 1));
            $BUF_record["remboursement_excp_ccam"] = trim(substr($buffer, 115, 1));
            if (get_numrss($BUF_record["no_rss"]) == 0) {
                $BUF_record["no_rss"] = $rsf_last_RSS;
            }
            $BUF_record["ok"] = TRUE;
            

            break;
        case "2008" :
            $BUF_record["BUF_offsets"] = $rsf_offsets_2008_M;
            
            $BUF_record["no_rss"] = trim(substr($buffer, 10, 20));
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 30, 13));
            $BUF_record["cle_immatriculation_assure"] = trim(substr($buffer, 43, 2));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 45, 3));
            $BUF_record["no_facture"] = trim(substr($buffer, 48, 9));
            $BUF_record["immatriculation_indiv"] = "";
            $BUF_record["cle_immatriculation_indiv"] = "";
            $BUF_record["mode_traitement"] = trim(substr($buffer, 57, 2));
            $BUF_record["discpline_prestation"] = trim(substr($buffer, 59, 3));
            $BUF_record["date_acte"] = trim(substr($buffer, 62, 8));
            $BUF_record["code_acte"] = trim(substr($buffer, 70, 7));
            $BUF_record["extension_ccam"] = trim(substr($buffer, 83, 1));
            $BUF_record["activite_ccam"] = trim(substr($buffer, 84, 1));
            $BUF_record["phase_ccam"] = trim(substr($buffer, 85, 1));
            $BUF_record["modificateur_ccam_1"] = trim(substr($buffer, 86, 1));
            $BUF_record["modificateur_ccam_2"] = trim(substr($buffer, 87, 1));
            $BUF_record["modificateur_ccam_3"] = trim(substr($buffer, 88, 1));
            $BUF_record["modificateur_ccam_4"] = trim(substr($buffer, 89, 1));
            $BUF_record["association_nonprevue_ccam"] = trim(substr($buffer, 90, 1));
            $BUF_record["remboursement_excp_ccam"] = trim(substr($buffer, 91, 1));
            if (get_numrss($BUF_record["no_rss"]) == 0) {
                $BUF_record["no_rss"] = $rsf_last_RSS;
            }
            $BUF_record["ok"] = TRUE;
            

            break;
        case "2008B" :
            $BUF_record["BUF_offsets"] = $rsf_offsets_2008B_M;
            
            $BUF_record["no_rss"] = trim(substr($buffer, 10, 20));
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 30, 13));
            $BUF_record["cle_immatriculation_assure"] = trim(substr($buffer, 43, 2));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 45, 3));
            $BUF_record["no_facture"] = trim(substr($buffer, 48, 9));
            $BUF_record["immatriculation_indiv"] = "";
            $BUF_record["cle_immatriculation_indiv"] = "";
            $BUF_record["mode_traitement"] = trim(substr($buffer, 57, 2));
            $BUF_record["discpline_prestation"] = trim(substr($buffer, 59, 3));
            $BUF_record["date_acte"] = trim(substr($buffer, 62, 8));
            $BUF_record["code_acte"] = trim(substr($buffer, 76, 7));
            $BUF_record["extension_ccam"] = trim(substr($buffer, 83, 1));
            $BUF_record["activite_ccam"] = trim(substr($buffer, 84, 1));
            $BUF_record["phase_ccam"] = trim(substr($buffer, 85, 1));
            $BUF_record["modificateur_ccam_1"] = trim(substr($buffer, 86, 1));
            $BUF_record["modificateur_ccam_2"] = trim(substr($buffer, 87, 1));
            $BUF_record["modificateur_ccam_3"] = trim(substr($buffer, 88, 1));
            $BUF_record["modificateur_ccam_4"] = trim(substr($buffer, 89, 1));
            $BUF_record["association_nonprevue_ccam"] = trim(substr($buffer, 90, 1));
            $BUF_record["remboursement_excp_ccam"] = trim(substr($buffer, 91, 1));
            if (get_numrss($BUF_record["no_rss"]) == 0) {
                $BUF_record["no_rss"] = $rsf_last_RSS;
            }
            $BUF_record["ok"] = TRUE;
            
            break;
        case "2006" :
            $BUF_record["BUF_offsets"] = $rsf_offsets_2006_M;
            
            $BUF_record["no_rss"] = trim(substr($buffer, 10, 7));
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 17, 13));
            $BUF_record["cle_immatriculation_assure"] = "";
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 30, 3));
            $BUF_record["no_facture"] = "";
            $BUF_record["immatriculation_indiv"] = "";
            $BUF_record["cle_immatriculation_indiv"] = "";
            $BUF_record["mode_traitement"] = trim(substr($buffer, 33, 2));
            $BUF_record["discpline_prestation"] = trim(substr($buffer, 35, 3));
            $BUF_record["date_acte"] = trim(substr($buffer, 38, 8));
            $BUF_record["code_acte"] = trim(substr($buffer, 46, 7));
            $BUF_record["extension_ccam"] = trim(substr($buffer, 59, 1));
            $BUF_record["activite_ccam"] = trim(substr($buffer, 60, 1));
            $BUF_record["phase_ccam"] = trim(substr($buffer, 61, 1));
            $BUF_record["modificateur_ccam_1"] = trim(substr($buffer, 62, 1));
            $BUF_record["modificateur_ccam_2"] = trim(substr($buffer, 63, 1));
            $BUF_record["modificateur_ccam_3"] = trim(substr($buffer, 64, 1));
            $BUF_record["modificateur_ccam_4"] = trim(substr($buffer, 65, 1));
            $BUF_record["association_nonprevue_ccam"] = trim(substr($buffer, 66, 1));
            $BUF_record["remboursement_excp_ccam"] = trim(substr($buffer, 67, 1));
            if (get_numrss($BUF_record["no_rss"]) == 0) {
                $BUF_record["no_rss"] = $rsf_last_RSS;
            }
            $BUF_record["ok"] = TRUE;
            break;
        case "2006B" :
            $BUF_record["BUF_offsets"] = $rsf_offsets_2006_M;
            
            $BUF_record["no_rss"] = trim(substr($buffer, 10, 7));
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 17, 13));
            $BUF_record["cle_immatriculation_assure"] = "";
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 30, 3));
            $BUF_record["no_facture"] = "";
            $BUF_record["immatriculation_indiv"] = "";
            $BUF_record["cle_immatriculation_indiv"] = "";
            $BUF_record["mode_traitement"] = trim(substr($buffer, 33, 2));
            $BUF_record["discpline_prestation"] = trim(substr($buffer, 35, 3));
            $BUF_record["date_acte"] = trim(substr($buffer, 38, 8));
            $BUF_record["code_acte"] = trim(substr($buffer, 52, 7));
            $BUF_record["extension_ccam"] = trim(substr($buffer, 59, 1));
            $BUF_record["activite_ccam"] = trim(substr($buffer, 60, 1));
            $BUF_record["phase_ccam"] = trim(substr($buffer, 61, 1));
            $BUF_record["modificateur_ccam_1"] = trim(substr($buffer, 62, 1));
            $BUF_record["modificateur_ccam_2"] = trim(substr($buffer, 63, 1));
            $BUF_record["modificateur_ccam_3"] = trim(substr($buffer, 64, 1));
            $BUF_record["modificateur_ccam_4"] = trim(substr($buffer, 65, 1));
            $BUF_record["association_nonprevue_ccam"] = trim(substr($buffer, 66, 1));
            $BUF_record["remboursement_excp_ccam"] = trim(substr($buffer, 67, 1));
            if (get_numrss($BUF_record["no_rss"]) == 0) {
                $BUF_record["no_rss"] = $rsf_last_RSS;
            }
            $BUF_record["ok"] = TRUE;
            break;

        case "ACE2017" :
            $BUF_record["BUF_offsets"] = $rsf_ace_offsets_2017_M;
            
            $BUF_record["no_rss"] = 0;
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 19, 13));
            $BUF_record["cle_immatriculation_assure"] = trim(substr($buffer, 32, 2));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 34, 3));
            $BUF_record["no_facture"] = trim(substr($buffer, 37, 9));
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 37, 9));
            $BUF_record["immatriculation_indiv"] = trim(substr($buffer, 46, 13));
            $BUF_record["cle_immatriculation_indiv"] = trim(substr($buffer, 59, 2));
            $BUF_record["mode_traitement"] = trim(substr($buffer, 61, 2));
            $BUF_record["discpline_prestation"] = trim(substr($buffer, 63, 3));
            $BUF_record["date_acte"] = trim(substr($buffer, 66, 8));
            $BUF_record["code_acte"] = trim(substr($buffer, 74, 7));
            $BUF_record["extension_ccam"] = trim(substr($buffer, 87, 1));
            $BUF_record["activite_ccam"] = trim(substr($buffer, 88, 1));
            $BUF_record["phase_ccam"] = trim(substr($buffer, 89, 1));
            $BUF_record["modificateur_ccam_1"] = trim(substr($buffer, 90, 1));
            $BUF_record["modificateur_ccam_2"] = trim(substr($buffer, 91, 1));
            $BUF_record["modificateur_ccam_3"] = trim(substr($buffer, 92, 1));
            $BUF_record["modificateur_ccam_4"] = trim(substr($buffer, 93, 1));
            $BUF_record["association_nonprevue_ccam"] = trim(substr($buffer, 94, 1));
            $BUF_record["remboursement_excp_ccam"] = trim(substr($buffer, 95, 1));

            $BUF_record["no_rss"] = $rsf_last_RSS;

            $BUF_record["ok"] = TRUE;
            

            break;

        case "ACE2016" :
            $BUF_record["BUF_offsets"] = $rsf_ace_offsets_2016_M;
            
            $BUF_record["no_rss"] = 0;
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 19, 13));
            $BUF_record["cle_immatriculation_assure"] = trim(substr($buffer, 32, 2));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 34, 3));
            $BUF_record["no_facture"] = trim(substr($buffer, 37, 9));
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 37, 9));
            $BUF_record["immatriculation_indiv"] = "";
            $BUF_record["cle_immatriculation_indiv"] = "";
            $BUF_record["mode_traitement"] = trim(substr($buffer, 46, 2));
            $BUF_record["discpline_prestation"] = trim(substr($buffer, 48, 3));
            $BUF_record["date_acte"] = trim(substr($buffer, 51, 8));
            $BUF_record["code_acte"] = trim(substr($buffer, 59, 7));
            $BUF_record["extension_ccam"] = trim(substr($buffer, 72, 1));
            $BUF_record["activite_ccam"] = trim(substr($buffer, 73, 1));
            $BUF_record["phase_ccam"] = trim(substr($buffer, 74, 1));
            $BUF_record["modificateur_ccam_1"] = trim(substr($buffer, 75, 1));
            $BUF_record["modificateur_ccam_2"] = trim(substr($buffer, 76, 1));
            $BUF_record["modificateur_ccam_3"] = trim(substr($buffer, 77, 1));
            $BUF_record["modificateur_ccam_4"] = trim(substr($buffer, 78, 1));
            $BUF_record["association_nonprevue_ccam"] = trim(substr($buffer, 79, 1));
            $BUF_record["remboursement_excp_ccam"] = trim(substr($buffer, 80, 1));

            $BUF_record["no_rss"] = $rsf_last_RSS;

            $BUF_record["ok"] = TRUE;
            

            break;

        case "ACE2008" :
            $BUF_record["BUF_offsets"] = $rsf_ace_offsets_2008_M;
            
            $BUF_record["no_rss"] = 0;
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 10, 13));
            $BUF_record["cle_immatriculation_assure"] = trim(substr($buffer, 23, 2));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 25, 3));
            $BUF_record["no_facture"] = trim(substr($buffer, 28, 9));
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 28, 9));
            $BUF_record["immatriculation_indiv"] = "";
            $BUF_record["cle_immatriculation_indiv"] = "";
            $BUF_record["mode_traitement"] = trim(substr($buffer, 37, 2));
            $BUF_record["discpline_prestation"] = trim(substr($buffer, 39, 3));
            $BUF_record["date_acte"] = trim(substr($buffer, 42, 8));
            $BUF_record["code_acte"] = trim(substr($buffer, 50, 7));
            $BUF_record["extension_ccam"] = trim(substr($buffer, 63, 1));
            $BUF_record["activite_ccam"] = trim(substr($buffer, 64, 1));
            $BUF_record["phase_ccam"] = trim(substr($buffer, 65, 1));
            $BUF_record["modificateur_ccam_1"] = trim(substr($buffer, 66, 1));
            $BUF_record["modificateur_ccam_2"] = trim(substr($buffer, 67, 1));
            $BUF_record["modificateur_ccam_3"] = trim(substr($buffer, 68, 1));
            $BUF_record["modificateur_ccam_4"] = trim(substr($buffer, 69, 1));
            $BUF_record["association_nonprevue_ccam"] = trim(substr($buffer, 70, 1));
            $BUF_record["remboursement_excp_ccam"] = trim(substr($buffer, 71, 1));

            $BUF_record["no_rss"] = $rsf_last_RSS;

            $BUF_record["ok"] = TRUE;
            

            break;
        
        case "ACE2007" :
            $BUF_record["BUF_offsets"] = $rsf_ace_offsets_2007_M;
            
            $BUF_record["no_rss"] = 0;
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 17, 13));
            $BUF_record["immatriculation_indiv"] = "";
            $BUF_record["cle_immatriculation_indiv"] = "";
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 30, 3));
            $BUF_record["mode_traitement"] = trim(substr($buffer, 33, 2));
            $BUF_record["discpline_prestation"] = trim(substr($buffer, 35, 3));
            $BUF_record["date_acte"] = trim(substr($buffer, 38, 8));
            $BUF_record["code_acte"] = trim(substr($buffer, 46, 7));
            $BUF_record["extension_ccam"] = trim(substr($buffer, 59, 1));
            $BUF_record["activite_ccam"] = trim(substr($buffer, 60, 1));
            $BUF_record["phase_ccam"] = trim(substr($buffer, 61, 1));
            $BUF_record["modificateur_ccam_1"] = trim(substr($buffer, 62, 1));
            $BUF_record["modificateur_ccam_2"] = trim(substr($buffer, 63, 1));
            $BUF_record["modificateur_ccam_3"] = trim(substr($buffer, 64, 1));
            $BUF_record["modificateur_ccam_4"] = trim(substr($buffer, 65, 1));
            $BUF_record["association_nonprevue_ccam"] = trim(substr($buffer, 66, 1));
            $BUF_record["remboursement_excp_ccam"] = trim(substr($buffer, 67, 1));

            $BUF_record["no_rss"] = $rsf_last_RSS;

            $BUF_record["ok"] = TRUE;
            

            break;
        default :
            // nothing to do
        }
    }
    
    // RSF I (Mutation en sortie)
    if ($BUF_record["type_enregistrement"] == "I" && $qI == TRUE) {
    
        if ($ENV_TYPEETS == "1") {
            if ($buf_len > 100 ) { // 88 avant 2017 et 112 depuis
                $BUF_version = "2017";
            }
            else {
                $BUF_version = "2016";
            }
        }

        $BUF_record["finess"] = trim(substr($buffer, 1, 9));
        $BUF_record["no_rss"] = "";
        
        switch ($BUF_version) {
        case "2017" :
            $BUF_record["BUF_offsets"] = $rsf_offsets_2017_I;
            
            $BUF_record["no_rss"] = trim(substr($buffer, 19, 20));
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 39, 13));
            $BUF_record["cle_immatriculation_assure"] = trim(substr($buffer, 52, 2));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 54, 3));
            $BUF_record["no_facture"] = trim(substr($buffer, 57, 9));
            $BUF_record["immatriculation_indiv"] = trim(substr($buffer, 66, 13));
            $BUF_record["cle_immatriculation_indiv"] = trim(substr($buffer, 79, 2));
            $BUF_record["date_debut"] = trim(substr($buffer, 81, 8));
            $BUF_record["date_fin"] = trim(substr($buffer, 89, 8));
            $BUF_record["nature_interruption"] = trim(substr($buffer, 97, 1));
            $BUF_record["finess_dest"] = (int)trim(substr($buffer, 98, 14));
            if (get_numrss($BUF_record["no_rss"]) == 0) {
                $BUF_record["no_rss"] = $rsf_last_RSS;
            }
            $BUF_record["ok"] = TRUE;
            break;
        case "2016" :
                $BUF_record["BUF_offsets"] = $rsf_offsets_2017_I;
            
            $BUF_record["no_rss"] = trim(substr($buffer, 10, 20));
            $BUF_record["immatriculation_assure"] = trim(substr($buffer, 30, 13));
            $BUF_record["cle_immatriculation_assure"] = trim(substr($buffer, 43, 2));
            $BUF_record["rang_beneficiaire"] = trim(substr($buffer, 45, 3));
            $BUF_record["no_facture"] = trim(substr($buffer, 48, 9));
            $BUF_record["date_debut"] = trim(substr($buffer, 57, 8));
            $BUF_record["date_fin"] = trim(substr($buffer, 65, 8));
            $BUF_record["nature_interruption"] = trim(substr($buffer, 73, 1));
            $BUF_record["finess_dest"] = trim(substr($buffer, 74, 14));
            if (get_numrss($BUF_record["no_rss"]) == 0) {
                $BUF_record["no_rss"] = $rsf_last_RSS;
            }
            $BUF_record["ok"] = TRUE;

        break;
        default :
            // nothing to do
        }
    }
    
    

    if (isset($BUF_record["no_rss"])){
        // Correction des n°RSS préfixés par NRSS depuis M12 2016
        if(strpos($BUF_record["no_rss"], "NRSS0") !== false) {
            $BUF_record["no_rss"] = "00000000000000000000";
        }

        // constante RSS dans le n° de RSS
        $position = strpos($BUF_record["no_rss"], 'RSS');
        if ($position !== false) {
            $BUF_record["no_rss"] = str_replace("RSS","000",$BUF_record["no_rss"]);
        }
    }

    // remplacement de l'immatriculation de l'assuré si l'immatriculation individuelle est renseignée
    if (isset($BUF_record["immatriculation_indiv"]) && $BUF_record["immatriculation_indiv"] != "" && floatval($BUF_record["immatriculation_indiv"]) != 0) {
        $BUF_record["immatriculation_assure"] = $BUF_record["immatriculation_indiv"];
        $BUF_record["cle_immatriculation_assure"] = $BUF_record["cle_immatriculation_indiv"];
    }
	

	// remplacement de la valeur nul dans la discipline de prestation
	if (isset($BUF_record["discpline_prestation"]) && $BUF_record["discpline_prestation"] === "nul") {
		$BUF_record["discpline_prestation"] = "000";
	}
    
    return $BUF_record;
        

}


function read_rsf_partial_line($buffer) {

    global $ENV_TYPEETS;
    
    global $rsf_last_RSS;
    global $current_rsfa_index;

    global $rsf_offsets_2006_M;
    global $rsf_offsets_2008_B;
    global $rsf_offsets_2008_M;
    global $rsf_offsets_2008B_M;

    global $rsf_offsets_2017_B;
    global $rsf_offsets_2017_M;

    global $rsf_ace_offsets_2016_M;
    global $rsf_ace_offsets_2008_M;

    global $rsf_ace_offsets_2007_M;
    global $rsf_ace_offsets_2017_M;

    $BUF_record = array();
    
    $BUF_record["ok"] = FALSE;

    $buffer = Encoding::removeBOM($buffer);

    if (is_entete_empty($buffer)){
        $BUF_record["type_enregistrement"] = "ENTETE";
        return $BUF_record;
    }
    
    
    $BUF_record["type_enregistrement"] = trim(substr($buffer, 0, 1));
    
    // Special Saint laurent pb décalages
    if ($BUF_record["type_enregistrement"] == "A" && substr($buffer, 0, 10) == "A350002192") {
        if (trim(substr($buffer, 34, 25)) == "") {
            $BUF_record["type_enregistrement"] = "IGNORE";
        }
    }
            
    $buf_len = strlen($buffer); 
    
    // ENTETE RSF 
    if ($BUF_record["type_enregistrement"] == "A") {
    
        $current_rsfa_index++;
    
        if ($ENV_TYPEETS == "1") {
            $BUF_141 = trim(substr($buffer, 141, 100));
            
            if ($buf_len > 220) {
                $BUF_version = "2017";
            } else if ($BUF_141 == "") {
                $BUF_version = "2006";
            }
            else {
                $BUF_version = "2008";
            }
        }
        else {
            $BUF_137 = trim(substr($buffer, 136, 100));
            $BUF_155 = trim(substr($buffer, 155, 100)); //Format de mars 2016
                    
            if ($buf_len > 200) {
                $BUF_version = "ACE2017";
            } else if ($BUF_155 != "") {
                $BUF_version = "ACE2016";
            }
            else{
                if ($BUF_137 != "") {
                    $BUF_version = "ACE2007";
                    $annee_sortie = trim(substr($buffer, 69, 4));
                    if (intval($annee_sortie) >= 2008) {
                        $BUF_version = "ACE2009";
                    }
                    else {
                        $annee_sortie = trim(substr($buffer, 74, 4));
                        if ($annee_sortie == "2006" || $annee_sortie == "2007" || $annee_sortie == "2008") {
                            $BUF_version = "ACE2007I";
                        }
                    }
                }
                else {
                    $BUF_version = "ACE2008";
                }
            }

        }
        
        if ($BUF_version == "2017") {
            $BUF_record["no_rss"] = trim(substr($buffer, 19, 20));
            $BUF_record["ok"] = TRUE;       
        }       
        if ($BUF_version == "2008") {
            $BUF_record["no_rss"] = trim(substr($buffer, 10, 20));
            $BUF_record["ok"] = TRUE;       
        }
        if ($BUF_version == "2006") {
            $BUF_record["no_rss"] = trim(substr($buffer, 10, 7));
            $BUF_record["ok"] = TRUE;       
        }
        if ($BUF_version == "ACE2017") {
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 39, 9));
            $BUF_record["no_rss"] = 0;
            $BUF_record["no_rss"] = '9' . str_pad(trim($current_rsfa_index), 8, '0', STR_PAD_LEFT);
            $BUF_record["ok"] = TRUE;       
        }           
        if ($BUF_version == "ACE2016") {
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 39, 9));
            $BUF_record["no_rss"] = 0;
            $BUF_record["no_rss"] = '9' . str_pad(trim($current_rsfa_index), 8, '0', STR_PAD_LEFT);
            $BUF_record["ok"] = TRUE;       
        }
        if ($BUF_version == "ACE2009") {
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 30, 9));
            $BUF_record["no_rss"] = 0;
            //if (get_numrss($BUF_record["no_rss"]) == 0) {
                // $BUF_record["no_rss"] = trim($current_rsfa_index + 99000000000);
                // $BUF_record["no_rss"] = '99' . str_pad(trim($current_rsfa_index), 9, '0', STR_PAD_LEFT);
                $BUF_record["no_rss"] = '9' . str_pad(trim($current_rsfa_index), 8, '0', STR_PAD_LEFT);
            //}
            $BUF_record["ok"] = TRUE;       
        }
        if ($BUF_version == "ACE2008") {
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 30, 9));
            $BUF_record["no_rss"] = 0;
            //if (get_numrss($BUF_record["no_rss"]) == 0) {
                // $BUF_record["no_rss"] = trim($current_rsfa_index + 99000000000);
                $BUF_record["no_rss"] = '9' . str_pad(trim($current_rsfa_index), 8, '0', STR_PAD_LEFT);
            //}
            $BUF_record["ok"] = TRUE;       
        }
        if ($BUF_version == "ACE2007") {
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 10, 9));
            $BUF_record["no_facture"] = trim(substr($buffer, 42, 9));
            $BUF_record["no_rss"] = 0;
            //if (get_numrss($BUF_record["no_rss"]) == 0) {
                // $BUF_record["no_rss"] = trim($current_rsfa_index + 99000000000);
                $BUF_record["no_rss"] = '9' . str_pad(trim($current_rsfa_index), 8, '0', STR_PAD_LEFT);
            //}
            $BUF_record["ok"] = TRUE;       
        }
        if ($BUF_version == "ACE2007I") {
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 10, 9));
            $BUF_record["no_facture"] = trim(substr($buffer, 44, 9));
            $BUF_record["no_rss"] = 0;
            //if (get_numrss($BUF_record["no_rss"]) == 0) {
                // $BUF_record["no_rss"] = trim($current_rsfa_index + 99000000000);
                $BUF_record["no_rss"] = '9' . str_pad(trim($current_rsfa_index), 8, '0', STR_PAD_LEFT);
            //}
            $BUF_record["ok"] = TRUE;       
        }
    }
    
    
    // RSF B plein
    if ($BUF_record["type_enregistrement"] == "B") {
    
        if ($ENV_TYPEETS == "1") {
            $BUF_130 = trim(substr($buffer, 130, 100));
            
            if ($buf_len > 180 ) {
                $BUF_version = "2017";
            }
            else if ($BUF_130 == "") {
                $BUF_version = "2006";
            }
            else {
                $BUF_version = "2008";
            }
        }
        else {
            $BUF_115 = trim(substr($buffer, 115, 100)); //Format de mars 2016
            
            if ($buf_len > 150 ) {
                $BUF_version = "ACE2017";
            }
            else if ($BUF_115 != "") {
                    $BUF_version = "ACE2016";
            }
            else {
                    $BUF_version = "ACE2008";
            }   
        }

        if ($BUF_version == "2017") {
            $BUF_record["BUF_offsets"] = $rsf_offsets_2017_B;
            
            $BUF_record["no_rss"] = trim(substr($buffer, 19, 20));
            $BUF_record["code_acte"] = trim(substr($buffer, 105, 5));
            $BUF_record["no_ghs"] = trim(substr($buffer, 167, 4));
            $BUF_record["ok"] = TRUE;
        }
        if ($BUF_version == "2008") {
            $BUF_record["BUF_offsets"] = $rsf_offsets_2008_B;
            
            $BUF_record["no_rss"] = trim(substr($buffer, 10, 20));
            $BUF_record["code_acte"] = trim(substr($buffer, 78, 5));
            $BUF_record["no_ghs"] = trim(substr($buffer, 139, 4));
            $BUF_record["ok"] = TRUE;
        }
        if ($BUF_version == "2006") {
            $BUF_record["no_rss"] = trim(substr($buffer, 10, 7));
            $BUF_record["code_acte"] = trim(substr($buffer, 54, 5));
            $BUF_record["no_ghs"] = trim(substr($buffer, 115, 4));
            $BUF_record["ok"] = TRUE;
        }
        if ($BUF_version == "ACE2017") {
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 37, 9));
            $BUF_record["code_acte"] = trim(substr($buffer, 77, 5));
            $BUF_record["no_rss"] = 0;
            $BUF_record["no_rss"] = $rsf_last_RSS;
            $BUF_record["ok"] = TRUE;           
        }           
        if ($BUF_version == "ACE2008") {
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 30, 9));
            $BUF_record["code_acte"] = trim(substr($buffer, 53, 5));
            $BUF_record["no_rss"] = 0;
            $BUF_record["no_rss"] = $rsf_last_RSS;
            $BUF_record["ok"] = TRUE;       
        }

        if ($BUF_version == "ACE2016") {
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 39, 9));
            $BUF_record["no_rss"] = 0;
            $BUF_record["no_rss"] = $rsf_last_RSS;
            $BUF_record["code_acte"] = trim(substr($buffer, 62, 5));
            $BUF_record["ok"] = TRUE;
        }
        
    }
    
    // RSF B plein
    if ($BUF_record["type_enregistrement"] == "C") {
    
        if ($ENV_TYPEETS == "1") {
            $BUF_version = "NONE";
        }
        else {
            $BUF_version = "NONE";
            // $BUF_58 = trim(substr($buffer, 58, 2));
            $BUF_49 = trim(substr($buffer, 49, 2));
            // Année 20xx (année presta) sur les caractères 59 et 60 et un caractère alpha sur le caractère 63
            if (trim(substr($buffer, 58, 2)) == "20" && !is_numeric(trim(substr($buffer, 62, 1)))) {
                $BUF_version = "ACE2016";
            } 
            else if ($BUF_49 == "20" && !is_numeric(trim(substr($buffer, 53, 1)))) {
                $BUF_version = "ACE2008";
            } 
            else {
                $BUF_43 = trim(substr($buffer, 49, 2));
                if ($BUF_43 == "20") {
                    //$BUF_version = "ACE2007";
                }
            }
        }
        if ($BUF_version == "ACE2016") {
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 37, 9));
            $BUF_record["code_acte"] = trim(substr($buffer, 62, 5));
            $BUF_record["no_rss"] = 0;
            $BUF_record["no_rss"] = $rsf_last_RSS;
            $BUF_record["ok"] = TRUE;   
        }
        else if ($BUF_version == "ACE2008") {
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 30, 9));
            $BUF_record["code_acte"] = trim(substr($buffer, 53, 5));
            $BUF_record["no_rss"] = 0;
            $BUF_record["no_rss"] = $rsf_last_RSS;
            $BUF_record["ok"] = TRUE;       
        }
        
    }
    
    // actes CCAM
    if ($BUF_record["type_enregistrement"] == "M" && $ENV_TYPEETS != "1") {
        
    
        if ($ENV_TYPEETS == "1") {
            $BUF_46 = trim(substr($buffer, 46, 1));
            $BUF_70 = trim(substr($buffer, 70, 1));
            $BUF_76 = trim(substr($buffer, 76, 1));
            if ($buf_len > 145 ) {
                $BUF_version = "2017";
            }
            else if ($BUF_70 >= "A" && $BUF_70 <= "Z") {
                $BUF_version = "2008";
            }
            else {
                if ($BUF_76 >= "A" && $BUF_76 <= "Z" && trim($BUF_70) == "") {
                    $BUF_version = "2008B";
                }
                else {
                    if (trim($BUF_46) != "") {
                        $BUF_version = "2006";
                    }
                    else {
                        $BUF_version = "2006B";
                    }
                }
            }
        }
        else {
            $BUF_55 = trim(substr($buffer, 55, 2)); // format 2016 doit donner 20 pour debut date sur l'année 
            $BUF_46 = trim(substr($buffer, 46, 2));
            if ($buf_len > 125) {
                $BUF_version = "ACE2017";
            } else if (trim($BUF_55) == "20"  && trim(substr($buffer, 53, 2)) < 13 && trim(substr($buffer, 51, 2)) < 32 && !is_numeric(trim(substr($buffer, 53, 2))) ) {
                $BUF_version = "ACE2016";
            }
            else{
                if (trim($BUF_46) == "20") {
                    $BUF_version = "ACE2008";
                }
                else {
                    $BUF_version = "ACE2007";
                }
            }   
        }


        $BUF_record["finess"] = trim(substr($buffer, 1, 9));
        $BUF_record["no_rss"] = "";
        
        if ($BUF_version == "2017") {
            $BUF_record["BUF_offsets"] = $rsf_offsets_2017_M;
            
            $BUF_record["no_rss"] = trim(substr($buffer, 19, 20));
            $BUF_record["no_facture"] = trim(substr($buffer, 57, 9));
            $BUF_record["code_acte"] = trim(substr($buffer, 94, 7));
            if (get_numrss($BUF_record["no_rss"]) == 0) {
                $BUF_record["no_rss"] = $rsf_last_RSS;
            }
            $BUF_record["ok"] = TRUE;
            

        }
        if ($BUF_version == "2008") {
            $BUF_record["BUF_offsets"] = $rsf_offsets_2008_M;
            
            $BUF_record["no_rss"] = trim(substr($buffer, 10, 20));
            $BUF_record["no_facture"] = trim(substr($buffer, 48, 9));
            $BUF_record["code_acte"] = trim(substr($buffer, 70, 7));
            if (get_numrss($BUF_record["no_rss"]) == 0) {
                $BUF_record["no_rss"] = $rsf_last_RSS;
            }
            $BUF_record["ok"] = TRUE;
            

        }
        if ($BUF_version == "2008B") {
            $BUF_record["BUF_offsets"] = $rsf_offsets_2008B_M;
            
            $BUF_record["no_rss"] = trim(substr($buffer, 10, 20));
            $BUF_record["no_facture"] = trim(substr($buffer, 48, 9));
            $BUF_record["code_acte"] = trim(substr($buffer, 76, 7));
            if (get_numrss($BUF_record["no_rss"]) == 0) {
                $BUF_record["no_rss"] = $rsf_last_RSS;
            }
            $BUF_record["ok"] = TRUE;
            
        }
        if ($BUF_version == "2006") {
            $BUF_record["BUF_offsets"] = $rsf_offsets_2006_M;
            
            $BUF_record["no_rss"] = trim(substr($buffer, 10, 7));
            $BUF_record["no_facture"] = "";
            $BUF_record["code_acte"] = trim(substr($buffer, 46, 7));
            if (get_numrss($BUF_record["no_rss"]) == 0) {
                $BUF_record["no_rss"] = $rsf_last_RSS;
            }
            $BUF_record["ok"] = TRUE;
        }
        if ($BUF_version == "2006B") {
            $BUF_record["BUF_offsets"] = $rsf_offsets_2006_M;
            
            $BUF_record["no_rss"] = trim(substr($buffer, 10, 7));
            $BUF_record["no_facture"] = "";
            $BUF_record["code_acte"] = trim(substr($buffer, 52, 7));
            if (get_numrss($BUF_record["no_rss"]) == 0) {
                $BUF_record["no_rss"] = $rsf_last_RSS;
            }
            $BUF_record["ok"] = TRUE;
        }
        if ($BUF_version == "ACE2017") {
            $BUF_record["BUF_offsets"] = $rsf_ace_offsets_2017_M;
            
            $BUF_record["no_rss"] = 0;
            $BUF_record["no_facture"] = trim(substr($buffer, 37, 9));
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 37, 9));
            $BUF_record["code_acte"] = trim(substr($buffer, 74, 7));
            $BUF_record["no_rss"] = $rsf_last_RSS;
            $BUF_record["ok"] = TRUE;
        }
        if ($BUF_version == "ACE2016") {
            $BUF_record["BUF_offsets"] = $rsf_ace_offsets_2016_M;
            
            $BUF_record["no_rss"] = 0;
            $BUF_record["no_facture"] = trim(substr($buffer, 37, 9));
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 37, 9));
            $BUF_record["code_acte"] = trim(substr($buffer, 59, 7));
            $BUF_record["no_rss"] = $rsf_last_RSS;
            $BUF_record["ok"] = TRUE;
        }
        if ($BUF_version == "ACE2008") {
            $BUF_record["BUF_offsets"] = $rsf_ace_offsets_2008_M;
            
            $BUF_record["no_rss"] = 0;
            $BUF_record["no_facture"] = trim(substr($buffer, 28, 9));
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 28, 9));
            $BUF_record["code_acte"] = trim(substr($buffer, 50, 7));
            $BUF_record["no_rss"] = $rsf_last_RSS;
            $BUF_record["ok"] = TRUE;
        }
        if ($BUF_version == "ACE2007") {
            $BUF_record["BUF_offsets"] = $rsf_ace_offsets_2007_M;
            
            $BUF_record["no_rss"] = 0;
            $BUF_record["code_acte"] = trim(substr($buffer, 46, 7));
            $BUF_record["no_rss"] = $rsf_last_RSS;
            $BUF_record["ok"] = TRUE;
        }
        
    }
    
    // constante RSS dans le n° de RSS
    if (isset($BUF_record["no_rss"])){
        $position = strpos($BUF_record["no_rss"], 'RSS');
        if ($position !== false) {
            $BUF_record["no_rss"] = str_replace("RSS","000",$BUF_record["no_rss"]);
        }
    }


    
    return $BUF_record;
        

}

/**
 *
 * FICHSUP transports
 * Type enregistrement G61
 * Format dans le manuel du logiciel FICHSUP produit par l'ATIH
*/
function read_tsp_line($buffer) {
    
    global $tsp_offsets_2019;
    
    $BUF_record = array();
    
    $buffer = Encoding::removeBOM($buffer);

    $BUF_record["ok"] = FALSE;
    $BUF_record["type_fichier"] = trim(substr($buffer, 9, 3));   // G61 normalement
    
    if ($BUF_record["type_fichier"] == 'G61') {
        $BUF_record["BUF_offsets"]  = $tsp_offsets_2019;
        $BUF_record["ok"]           = TRUE;
        $BUF_record["finess"]       = trim(substr($buffer, 0, 9));
        $BUF_record["annee"]        = trim(substr($buffer, 12, 4)); // Format AAAA
        $BUF_record["periode"]      = trim(substr($buffer, 16, 2)); // Ex : 10 pour la transmission d'octobre
        $BUF_record["code"]         = trim(substr($buffer, 18, 3)); // Valeur égale à TSE ou TDE
        $BUF_record["nb_sejours"]   = trim(substr($buffer, 21, 10));
    }
    
    return $BUF_record;
}

/**
* type enregistrement :
* 02 : DMI
* 03 : Prélèvement d'organe
* 04 : Prestations inter établissements
* 06 : médicaments hors ATU
* 07 : dialyse péritonéale (suppléments DIP)
* 09 : médicaments avec ATU
* 10 : médicament anti-thrombotique
* 51 : PIP
* 52 : ORP maladies rares
* 99 : enquêtes
*/
function read_fcp_line($buffer) {

    global $fcp_dmi_offsets_2007;
    global $fcp_dmi_offsets_2008;
    global $fcp_ucd_offsets_2007;
    global $fcp_ucd_offsets_2008;

    $BUF_record = array();

    $buffer = Encoding::removeBOM($buffer);


    $BUF_record["ok"] = FALSE;  

    $BUF_record["type_enregistrement"] = "";
    $version_annee = "";
    
    $BUF_42 = trim(substr($buffer, 42, 100));
    $BUF_45 = trim(substr($buffer, 45, 100));
    $BUF_35 = trim(substr($buffer, 35, 4));
    
    if ($BUF_42 == "") {
        $BUF_record["type_enregistrement"] = "02";
        $version_annee = "2007";
    }
    else {
        if ($BUF_45 == "") {
            $BUF_record["type_enregistrement"] = "01";
            $version_annee = "2007";
        }
        else {
            $BUF_record["type_enregistrement"] = trim(substr($buffer, 9, 2));
            if ($BUF_35 == "2009" || $BUF_35 == "2010" || $BUF_35 == "2011") {
                $version_annee = "2008B";
            }
            else {
                $version_annee = "2008";
            }
        }
    }
    
    // Initialisation variables
    $BUF_record["finess"]                  = "";
    $BUF_record["type_prestation"]         = "";
    $BUF_record["no_sejour_administratif"] = "";
    $BUF_record["no_rum"]                  = "1";
    $BUF_record["date_debut"]              = "";
    $BUF_record["date_fin"]                = "";
    $BUF_record["code"]                    = "";
    $BUF_record["nombre"]                  = "";
    $BUF_record["montant_paye"]            = "";
    $BUF_record["indication"]              = "";
    
    if ($version_annee == "2007" && $BUF_record["type_enregistrement"] == "02") {
        $BUF_record["BUF_offsets"] = $fcp_dmi_offsets_2007;
        
        $BUF_record["finess"] = trim(substr($buffer, 0, 9));
        $BUF_record["type_prestation"] = "02";
        $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 9, 20));
        $BUF_record["no_rum"] = "0";
        $BUF_record["date_debut"] = "20991231";
        $BUF_record["date_fin"] = "20991231";
        $BUF_record["code"] = trim(substr($buffer, 29, 9));
        $BUF_record["nombre"] = trim(substr($buffer, 38, 4));
        $BUF_record["montant_paye"] = "0";
        
        $BUF_record["ok"] = TRUE;       
    }
    if ($version_annee == "2008B" && $BUF_record["type_enregistrement"] == "02") {
        $BUF_record["BUF_offsets"] = $fcp_dmi_offsets_2008;
        
        $BUF_record["finess"] = trim(substr($buffer, 0, 9));
        $BUF_record["type_prestation"] = trim(substr($buffer, 9, 2));
        $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 11, 20));
        $BUF_record["no_rum"] = 1;
        $BUF_record["date_debut"] = trim(substr($buffer, 31, 8));
        $BUF_record["date_fin"] = trim(substr($buffer, 31, 8));
        $BUF_record["code"] = trim(substr($buffer, 39, 15));
        $BUF_record["nombre"] = trim(substr($buffer, 54, 10));
        $BUF_record["montant_paye"] = trim(substr($buffer, 64, 10));
        
        $BUF_record["ok"] = TRUE;       
    }
    if ($version_annee == "2008" && $BUF_record["type_enregistrement"] == "02") {
        $BUF_record["BUF_offsets"] = $fcp_dmi_offsets_2008;
        
        $BUF_record["finess"] = trim(substr($buffer, 0, 9));
        $BUF_record["type_prestation"] = trim(substr($buffer, 9, 2));
        $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 11, 20));
        $BUF_record["no_rum"] = trim(substr($buffer, 31, 10));
        $BUF_record["date_debut"] = trim(substr($buffer, 41, 8));
        $BUF_record["date_fin"] = trim(substr($buffer, 49, 8));
        if ($BUF_record["date_fin"] == "") {
            $BUF_record["date_fin"] = $BUF_record["date_debut"];
        }
        $BUF_record["code"] = trim(substr($buffer, 57, 15));
        $BUF_record["nombre"] = trim(substr($buffer, 72, 10));
        $BUF_record["montant_paye"] = trim(substr($buffer, 82, 10));
        
        $BUF_record["ok"] = TRUE;       
    }
    if ($version_annee == "2007" && $BUF_record["type_enregistrement"] == "01") {
        $BUF_record["BUF_offsets"] = $fcp_ucd_offsets_2007;
        
        $BUF_record["finess"] = trim(substr($buffer, 0, 9));
        $BUF_record["type_prestation"] = "02";
        $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 9, 20));
        $BUF_record["no_rum"] = "0";
        $BUF_record["date_debut"] = "20991231";
        $BUF_record["date_fin"] = "20991231";
        $BUF_record["code"] = trim(substr($buffer, 29, 9));
        $BUF_record["nombre"] = trim(substr($buffer, 38, 7));
        $BUF_record["montant_paye"] = "0";
        
        $BUF_record["ok"] = TRUE;       
    }
    if ($version_annee == "2008" && $BUF_record["type_enregistrement"] == "01") {
        $BUF_record["BUF_offsets"] = $fcp_ucd_offsets_2008;
        
        $BUF_record["finess"] = trim(substr($buffer, 0, 9));
        $BUF_record["type_prestation"] = trim(substr($buffer, 9, 2));
        $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 11, 20));
        $BUF_record["no_rum"] = trim(substr($buffer, 31, 10));
        $BUF_record["date_debut"] = trim(substr($buffer, 41, 8));
        $BUF_record["date_fin"] = trim(substr($buffer, 49, 8));
        if ($BUF_record["date_fin"] == "") {
            $BUF_record["date_fin"] = $BUF_record["date_debut"];
        }
        $BUF_record["code"] = trim(substr($buffer, 57, 15));
        $BUF_record["nombre"] = trim(substr($buffer, 72, 10));
        $BUF_record["montant_paye"] = trim(substr($buffer, 82, 10));
        
        $BUF_record["ok"] = TRUE;
    }
    if ($version_annee == "2008B" && $BUF_record["type_enregistrement"] == "01") {
        $BUF_record["BUF_offsets"] = $fcp_ucd_offsets_2008;
        
        $BUF_record["finess"] = trim(substr($buffer, 0, 9));
        $BUF_record["type_prestation"] = trim(substr($buffer, 9, 2));
        $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 11, 20));
        $BUF_record["no_rum"] = "1";
        $BUF_record["date_debut"] = trim(substr($buffer, 31, 8));
        $BUF_record["date_fin"] = trim(substr($buffer, 31, 8));
        $BUF_record["code"] = trim(substr($buffer, 39, 15));
        $BUF_record["nombre"] = trim(substr($buffer, 54, 10));
        $BUF_record["montant_paye"] = trim(substr($buffer, 64, 10));
        
        $BUF_record["ok"] = TRUE;
    }
    if ($version_annee == "2008B" && $BUF_record["type_enregistrement"] == "06") {
        //$BUF_record["type_enregistrement"] = "01";
        $BUF_record["BUF_offsets"] = $fcp_ucd_offsets_2008;
        $BUF_record["finess"] = trim(substr($buffer, 0, 9));
        $BUF_record["type_prestation"] = trim(substr($buffer, 9, 2));
        $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 11, 20));
        $BUF_record["no_rum"] = "1";
        $BUF_record["date_debut"] = trim(substr($buffer, 31, 8));
        $BUF_record["date_fin"] = trim(substr($buffer, 31, 8));
        // Prise en compte des codes UCD à 7 et à 13 (cf. IC-3203 et IC-5267).
        $BUF_record["code"] = (strlen(trim(substr($buffer, 39, 15))) == 7 ? trim(substr($buffer, 39, 15)) : substr(str_pad(trim(substr($buffer, 39, 15)), 15, '0', STR_PAD_LEFT), 7, 7));
        $BUF_record["nombre"] = trim(substr($buffer, 54, 10));
        $BUF_record["montant_paye"] = trim(substr($buffer, 64, 10));
        $BUF_record["ok"] = TRUE;
    }
    if ($version_annee == "2008" && ($BUF_record["type_enregistrement"] == "06"|| $BUF_record["type_enregistrement"] == "09")) {
        // MED.TXT (Ucd en SUS) ou MEDATU.txt (Anciennemnet ATU, depuis 2021 AP-AC)
        //$BUF_record["type_enregistrement"] = "01";
        $BUF_record["BUF_offsets"] = $fcp_ucd_offsets_2008;
        $BUF_record["finess"] = trim(substr($buffer, 0, 9));
        $BUF_record["type_prestation"] = trim(substr($buffer, 9, 2));
        $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 11, 20));
        $BUF_record["no_rum"] = "1";
        $BUF_record["date_debut"] = trim(substr($buffer, 31, 8));
        $BUF_record["date_fin"] = trim(substr($buffer, 31, 8));
        // Prise en compte des codes UCD à 7 et à 13 (cf. IC-3203 et IC-5267).
        $BUF_record["code"] = (strlen(trim(substr($buffer, 39, 15))) == 7 ? trim(substr($buffer, 39, 15)) : substr(str_pad(trim(substr($buffer, 39, 15)), 15, '0', STR_PAD_LEFT), 7, 7));
        $BUF_record["nombre"] = trim(substr($buffer, 54, 10));
        $BUF_record["montant_paye"] = trim(substr($buffer, 64, 10));
        $BUF_record["indication"] = trim(substr($buffer, 75, 7));
        $BUF_record["ok"] = TRUE;
    }
    
    $BUF_record["nombre"] = str_replace(" ", "0", $BUF_record["nombre"]);
    
    return $BUF_record;

}



function read_tra_line($buffer) {

    global $ENV_TYPEETS;

    $BUF_record = array();

    $buffer = Encoding::removeBOM($buffer);

    
    $BUF_record["ok"] = FALSE;  

    $BUF_record["type_enregistrement"] = "";
    $version_annee = "";

    $BUF_77 = trim(substr($buffer, 77, 10));
    $BUF_62 = trim(substr($buffer, 62, 10));
    
	if (trim(substr($buffer, 9, 1)) == ";") {
		$BUF_record["type_enregistrement"] = "TRA";
		$version_annee = "2023";
        if (trim(substr($buffer, 21, 5) == "NRSS0")) { // Correspond aux externes
            $BUF_record["type_enregistrement"] = "NONE";
        }
	}
    else if (trim(substr($buffer, 10, 1)) == ";") {
            $BUF_record["type_enregistrement"] = "TRA";
            $version_annee = "2023V2";
            if (trim(substr($buffer, 21, 5) == "NRSS0")) {
				$BUF_record["type_enregistrement"] = "NONE";
			}
    }
	else {
        //Ancienne version
		if ($BUF_77 == "") {
			if ($BUF_62 == "") {
				$BUF_record["type_enregistrement"] = "TRA";
				$version_annee = "2007";
			}
			else {
				$BUF_record["type_enregistrement"] = "TRA";
				$version_annee = "2008";
			}
		}
		else {
			$BUF_record["type_enregistrement"] = "TRA";
			$version_annee = "2009";
		}
		
		
		if ($BUF_record["type_enregistrement"] == "TRA") {
			if (trim(substr($buffer, 10, 5) == "NRSS0")) {
				$BUF_record["type_enregistrement"] = "NONE";
			}
		}
	}
	
    if ($BUF_record["type_enregistrement"] == "TRA") {
        $BUF_record["doControlTRA_GHM"] = false;
        if ($version_annee == "2023V2" ) {
            $BUF_record["no_rsa"] = trim(substr($buffer, 0, 10));
            $BUF_record["no_rss"] = trim(substr($buffer, 11, 20));
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 32, 20));
            $BUF_record["ghm"] = trim(substr($buffer, 71, 6));
            $BUF_record["ligne_rss"] = 0;
            $BUF_record["ok"] = TRUE;
            $BUF_record["doControlTRA_GHM"] = true;
        }
		if ($version_annee == "2023" ) {
            $BUF_record["no_rsa"] = trim(substr($buffer, 10, 10));
            if ($ENV_TYPEETS === "1"){
                $BUF_record["no_rss"] = trim(substr($buffer, 21, 20));
                $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 42, 20));
            } else {
                $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 21, 20));
                $BUF_record["no_rss"] = trim(substr($buffer, 42, 20));
            }
            $BUF_record["ligne_rss"] = 0;
            $BUF_record["ghm"] = "";

            $BUF_record["ok"] = TRUE;
        }
        if ($version_annee == "2009" ) {
            $BUF_record["no_rsa"] = trim(substr($buffer, 0, 10));
            $BUF_record["ligne_rss"] = trim(substr($buffer, 30, 10));
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 40, 20));
            $BUF_record["ghm"] = trim(substr($buffer, 68, 6));

            $BUF_record["ok"] = TRUE;
        }
        
        if ($version_annee == "2008" ) {
            $BUF_record["no_rsa"] = trim(substr($buffer, 0, 10));
            $BUF_record["ligne_rss"] = trim(substr($buffer, 30, 10));
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 40, 20));
            $BUF_record["ghm"] = trim(substr($buffer, 68, 6));

            $BUF_record["ok"] = TRUE;
        }
        
        if ($version_annee == "2007" ) {
            $BUF_record["no_rsa"] = trim(substr($buffer, 0, 10));
            $BUF_record["ligne_rss"] = trim(substr($buffer, 17, 10));
            $BUF_record["no_sejour_administratif"] = trim(substr($buffer, 27, 20));
            $BUF_record["ghm"] = trim(substr($buffer, 55, 6));

            $BUF_record["ok"] = TRUE;
        }
    }

    return $BUF_record;

}

/**
 * Lit une ligne du fichier [finess].[annee].[mois].leg (Inclus dans le OUT.ZIP)
 * qui donne la liste d'erreurs de groupage applicable à compter du 1er janvier 2009
 * Le format est le suivant :
 * [Finess][Mois période][Année période][Numéro index RSA][Nombre d'erreurs][Code erreur 1]...[Code erreur N]
 */
function read_leg_line($buffer) {

    $BUF_record = array();

    $buffer = Encoding::removeBOM($buffer);


    $BUF_record["ok"] = FALSE;  

    $BUF_record["type_enregistrement"] = "";
    
    $leg_line = explode(';', $buffer);
    // Il doit y avoir au moins 6 colonnes dans une ligne de fichier LEG pour que le format soit respecté
    if (count($leg_line) >= 6 ) {
        // Vérifie si le nombre de colonnes est cohérent avec le nombre d'erreurs du RSA
        if(count($leg_line) == (5 + intval($leg_line[4]))) {
            $BUF_record["type_enregistrement"] = "LEG";
        }
    }
    
    if ($BUF_record["type_enregistrement"] == "LEG") {
        
        $BUF_record["finess"] = trim($leg_line[0]);
        $BUF_record["no_rsa"] = trim($leg_line[3]);
        // concatène tous les codes erreurs du rsa avc des points-virgules
        $BUF_record["codes"] = trim(implode(';', array_slice($leg_line, 5)));

        $BUF_record["ok"] = TRUE;       
    }

    return $BUF_record;
}


function read_rsa_line($buffer, $qAD = TRUE) {
    global $last_BUF_rss;
    global $last_BUF_rsa;
    global $rsa_offsets_215;
    global $rsa_offsets_222;
    global $rsa_offsets_223;
	global $rsa_offsets_226;
	global $rsa_offsets_227;
	global $rsa_offsets_228;
	global $rsa_offsets_229;

    global $annee_fin;
    global $annee_mois_fin;

    $BUF_record = array();

    $buffer = Encoding::removeBOM($buffer);


    if (is_entete_empty($buffer)){
        $BUF_record["type_enregistrement"] = "ENTETE";
        return $BUF_record;
    }
       
    $BUF_record["type_enregistrement"] = "RSA";
    
    if ($BUF_record["type_enregistrement"] == "RSA") {
        $BUF_record["supprdth"] = array();
        $BUF_record["finess"] = trim(substr($buffer, 0, 9));
        $BUF_record["version_format_rsa"] = trim(substr($buffer, 9, 3));
        $BUF_record["no_rss"] = "";
        $BUF_record["fmt_error"] = "";
        $BUF_record["top_uhcd"] = "";
        
        // Nb de suppl. de radiothérapie introduit dans le format RSA 218.
        // A zéro par défaut (pour rétro-compatibilité).
        $BUF_record["nb_rdth"] = '0'; 
        
        // Rétro-compatibilité Format 219 ------------------------------------------------------
        $BUF_aut_pgv_length = 0;
        $BUF_record["nb_aut_pgv"] = '0';
        $BUF_record["nb_sup_rap"] = '000';
        $BUF_record["nb_sup_ant"] = '000';
        // Rétro-compatibilité Format 222 ------------------------------------------------------
        $BUF_record["nombre_ivg_anterieures"] = "";
        $BUF_record["annee_ivg_precedente"] = "";
        $BUF_record["nombre_naissances_vivantes_anterieures"] = "";
        $BUF_record["top_valve_aortique"] = "";
        $BUF_record["type_generation_automatique"] = "0";
        $BUF_record["top_ghs_minore"] = "0";
        // -------------------------------------------------------------------------------------
        $BUF_record["nb_actes_9510"] = "000";
        $BUF_record["nb_actes_9511"] = "000";
        $BUF_record["nb_actes_9512"] = "000";
        $BUF_record["nb_actes_9515"] = "000";
        $BUF_record["nb_actes_9524"] = "000";
        $BUF_record["nb_actes_9621"] = "000";
        $BUF_record["nb_actes_9622"] = "000";
        $BUF_record["nb_actes_6523"] = "000";

        $BUF_record["annee_sortie"] = "0";


        switch ($BUF_record["version_format_rsa"]) {
            case "229" :
               // 229 - Applicable à compter de M03 2025
                $BUF_record["BUF_offsets"] = $rsa_offsets_229;
                $BUF_record["no_rsa"] = trim(substr($buffer, 12, 10));
                $BUF_record["version_format"] = trim(substr($buffer, 22, 3));
                $BUF_record["numero_tarif"] = trim(substr($buffer, 25, 3));
                $BUF_record["version_groupage"] = trim(substr($buffer, 28, 2));
                $BUF_record["ghm"] = trim(substr($buffer, 30, 6));
                $BUF_record["code_retour"] = trim(substr($buffer, 36, 3));
                $BUF_record["version_groupage_genrsa"] = trim(substr($buffer, 39, 2));
                $BUF_record["ghm_genrsa"] = trim(substr($buffer, 41, 6));
                $BUF_record["code_retour_genrsa"] = trim(substr($buffer, 47, 3));
                $BUF_record["nombre_rum"] = trim(substr($buffer, 50, 2));
                $BUF_record["age_annees"] = trim(substr($buffer, 52, 3));
                $BUF_record["age_jours"] = trim(substr($buffer, 55, 3));
                $BUF_record["sexe"] = trim(substr($buffer, 58, 1));
                $BUF_record["mode_entree"] = trim(substr($buffer, 59, 1));
                $BUF_record["provenance"] = trim(substr($buffer, 60, 1));
                $BUF_record["mois_sortie"]= trim(substr($buffer, 61, 6));
                $BUF_record["annee_sortie"] = trim(substr($buffer, 63, 4));
                $BUF_record["mode_sortie"] = trim(substr($buffer, 67, 1));
                $BUF_record["destination"] = trim(substr($buffer, 68, 1));
                $BUF_record["type_sejour"] = trim(substr($buffer, 69, 1));
                $BUF_record["duree_sejour"] = trim(substr($buffer, 70, 4));
                $BUF_record["code_geographique"] = substr($buffer, 74, 5);
                $BUF_record["poids_entree"] = trim(substr($buffer, 79, 4));
                $BUF_record["age_gestationnel"] = trim(substr($buffer, 83, 2));
                $BUF_record["delai_dernieres_regles"] = trim(substr($buffer, 85, 3));
                $BUF_record["nombre_seances"] = trim(substr($buffer, 93, 2));
                $BUF_record["igs2"] = "000";
                $BUF_record["ghs_genrsa"] = trim(substr($buffer, 95, 4));
                $BUF_record["nb_exh"] = trim(substr($buffer, 99, 4));
                $BUF_record["type_exb"] = trim(substr($buffer, 103, 1));
                $BUF_record["nb_exb"] = trim(substr($buffer, 104, 3));
                $BUF_record["forfait_dialyse"] = "";

                // Nouveauté non exploitée : Top Admission Maison de Naissance 0:NON / 1:OUI
                $BUF_record["top_adm_maison_naissance"] = trim(substr($buffer, 107, 1));
                // Nouveauté non exploitée : Top Radiation partielle Avastin 0:NON / 1:OUI
                $BUF_record["top_radiation_part_avastin"] = trim(substr($buffer, 108, 1));
                // Nouveauté non exploitée : Top Radiation partielle Alimta 0:NON / 1:OUI
                $BUF_record["top_radiation_partielle_alimta"] = trim(substr($buffer, 109, 1));

                $BUF_record["top_uhcd"] = trim(substr($buffer, 110, 1));
                // top_ghs_minore : 0 = non | 1 = oui
                $BUF_record["top_ghs_minore"] = trim(substr($buffer, 111, 1));
                $BUF_record["confirmation_codage"] = trim(substr($buffer, 112, 1));
                // Nouveauté non exploitée : Nombre d'autorisations d'unités médicales à portée globale valides (Nb_AutPGV)
                $BUF_record["nb_aut_pgv"] = trim(substr($buffer, 113, 1));
                // -------------------------------------------------------------------------------------
                $BUF_record["nb_sup_dialyse_1"] = trim(substr($buffer, 114, 3));
                $BUF_record["nb_sup_dialyse_2"] = trim(substr($buffer, 117, 3));
                $BUF_record["nb_sup_dialyse_3"] = trim(substr($buffer, 120, 3));
                $BUF_record["nb_sup_dialyse_4"] = trim(substr($buffer, 123, 3));
                $BUF_record["nb_sup_apherese"] = trim(substr($buffer, 126, 3));
                // Nouveauté : Nombre de suppléments radiothérapie pédiatrique -------------------------
                $BUF_record["nb_sup_rap"] = trim(substr($buffer, 129, 3));
                // -------------------------------------------------------------------------------------
                // Nouveauté : Nombre de suppléments antepartum ----------------------------------------
                $BUF_record["nb_sup_ant"] = trim(substr($buffer, 132, 3));
                // -------------------------------------------------------------------------------------
                $BUF_record["nb_rdth"] = trim(substr($buffer, 135, 1));
                // top_valve_aortique : 1 si date sortie >=15/08/2012 + type autorisation UM 60 + acte pose, blanc sinon
                $BUF_record["top_valve_aortique"] = trim(substr($buffer, 136, 1));
                // type_generation_automatique: 0 = pas de génération automatique | 1 = FFM, ATU, SE | 2 = médecin salariés | 3 = dialyse
                $BUF_record["type_generation_automatique"] = trim(substr($buffer, 137, 1));
                $BUF_record["ghs_hors_innovation"] = trim(substr($buffer, 95, 4));
                $BUF_record["nb_seances_avant_sros"] = "00";
                $BUF_record["nb_sup_hyperbare"] = trim(substr($buffer, 150, 3));
                $BUF_record["type_prestation_prelevement_organe"] = trim(substr($buffer, 153, 1));
                $BUF_record["nb_sup_sra"] = "000";
                $BUF_record["nb_sup_rea"] = trim(substr($buffer, 154, 3));
                $BUF_record["nb_sup_si"] = trim(substr($buffer, 157, 3));
                $BUF_record["nb_sup_stf"] = trim(substr($buffer, 160, 3));
                $BUF_record["nb_sup_ssc"] = "000";
                $BUF_record["nb_sup_usip"] = trim(substr($buffer, 163, 3));
                $BUF_record["nb_sup_src"] = trim(substr($buffer, 166, 3));
                $BUF_record["nb_sup_nn1"] = trim(substr($buffer, 169, 3));
                $BUF_record["nb_sup_nn2"] = trim(substr($buffer, 172, 3));
                $BUF_record["nb_sup_nn3"] = trim(substr($buffer, 175, 3));
                $BUF_record["nb_sup_rep"] = trim(substr($buffer, 178, 3));
                $BUF_record["passage_lit_sp"] = trim(substr($buffer, 181, 1));
                $BUF_record["type_machine_rdth"] = trim(substr($buffer, 182, 1));
                $BUF_record["type_dosimetrie"] = trim(substr($buffer, 183, 1));
                $BUF_record["numero_innovation"] = trim(substr($buffer, 184, 15));
                $BUF_record["nombre_ivg_anterieures"] = "";
                $BUF_record["annee_ivg_precedente"] = "";
                $BUF_record["nombre_naissances_vivantes_anterieures"] = "";
                $BUF_record["nb_sup_sdc"] = trim(substr($buffer, 199, 1));
                $BUF_record["nb_faisceaux"] = "";
                $BUF_record["no_rum_dp"] = trim(substr($buffer, 212, 2));
                $BUF_record["diagnostic_principal"] = trim(substr($buffer, 214, 6));
                $BUF_record["diagnostic_relie"] = trim(substr($buffer, 220, 6));
                $BUF_record["nb_das"] = trim(substr($buffer, 226, 4));

                $BUF_aut_pgv_length = 2;

                //DRUIDE 2023
                $BUF_start = 265;

                $BUF_record["ok"] = TRUE;
                break;
            case "228" :
            // 228 - Applicable à compter de M03 2021
            $BUF_record["BUF_offsets"] = $rsa_offsets_228;
            $BUF_record["no_rsa"] = trim(substr($buffer, 12, 10));
            $BUF_record["version_format"] = trim(substr($buffer, 22, 3));
            $BUF_record["numero_tarif"] = trim(substr($buffer, 25, 3));
            $BUF_record["version_groupage"] = trim(substr($buffer, 28, 2));
            $BUF_record["ghm"] = trim(substr($buffer, 30, 6));
            $BUF_record["code_retour"] = trim(substr($buffer, 36, 3));
            $BUF_record["version_groupage_genrsa"] = trim(substr($buffer, 39, 2));
            $BUF_record["ghm_genrsa"] = trim(substr($buffer, 41, 6));
            $BUF_record["code_retour_genrsa"] = trim(substr($buffer, 47, 3));
            $BUF_record["nombre_rum"] = trim(substr($buffer, 50, 2));
            $BUF_record["age_annees"] = trim(substr($buffer, 52, 3));
            $BUF_record["age_jours"] = trim(substr($buffer, 55, 3));
            $BUF_record["sexe"] = trim(substr($buffer, 58, 1));
            $BUF_record["mode_entree"] = trim(substr($buffer, 59, 1));
            $BUF_record["provenance"] = trim(substr($buffer, 60, 1));
            $BUF_record["mois_sortie"]= trim(substr($buffer, 61, 6));
            $BUF_record["annee_sortie"] = trim(substr($buffer, 63, 4));
            $BUF_record["mode_sortie"] = trim(substr($buffer, 67, 1));
            $BUF_record["destination"] = trim(substr($buffer, 68, 1));
            $BUF_record["type_sejour"] = trim(substr($buffer, 69, 1));
            $BUF_record["duree_sejour"] = trim(substr($buffer, 70, 4));
            $BUF_record["code_geographique"] = substr($buffer, 74, 5);
            $BUF_record["poids_entree"] = trim(substr($buffer, 79, 4));
            $BUF_record["age_gestationnel"] = trim(substr($buffer, 83, 2));
            $BUF_record["delai_dernieres_regles"] = trim(substr($buffer, 85, 3));
            $BUF_record["nombre_seances"] = trim(substr($buffer, 93, 2));
            $BUF_record["igs2"] = "000";
            $BUF_record["ghs_genrsa"] = trim(substr($buffer, 95, 4));
            $BUF_record["nb_exh"] = trim(substr($buffer, 99, 4));
            $BUF_record["type_exb"] = trim(substr($buffer, 103, 1));
            $BUF_record["nb_exb"] = trim(substr($buffer, 104, 3)); 
            $BUF_record["forfait_dialyse"] = "";

            // Nouveauté non exploitée : Top Admission Maison de Naissance 0:NON / 1:OUI
            $BUF_record["top_adm_maison_naissance"] = trim(substr($buffer, 107, 1));
            // Nouveauté non exploitée : Top Radiation partielle Avastin 0:NON / 1:OUI
            $BUF_record["top_radiation_part_avastin"] = trim(substr($buffer, 108, 1));
            // Nouveauté non exploitée : Top Radiation partielle Alimta 0:NON / 1:OUI
            $BUF_record["top_radiation_partielle_alimta"] = trim(substr($buffer, 109, 1));

            $BUF_record["top_uhcd"] = trim(substr($buffer, 110, 1));
            // top_ghs_minore : 0 = non | 1 = oui
            $BUF_record["top_ghs_minore"] = trim(substr($buffer, 111, 1));
            $BUF_record["confirmation_codage"] = trim(substr($buffer, 112, 1));
            // Nouveauté non exploitée : Nombre d'autorisations d'unités médicales à portée globale valides (Nb_AutPGV)
            $BUF_record["nb_aut_pgv"] = trim(substr($buffer, 113, 1));
            // -------------------------------------------------------------------------------------
            $BUF_record["nb_sup_dialyse_1"] = trim(substr($buffer, 114, 3));
            $BUF_record["nb_sup_dialyse_2"] = trim(substr($buffer, 117, 3));
            $BUF_record["nb_sup_dialyse_3"] = trim(substr($buffer, 120, 3));
            $BUF_record["nb_sup_dialyse_4"] = trim(substr($buffer, 123, 3));
            $BUF_record["nb_sup_apherese"] = trim(substr($buffer, 126, 3));
            // Nouveauté : Nombre de suppléments radiothérapie pédiatrique -------------------------
            $BUF_record["nb_sup_rap"] = trim(substr($buffer, 129, 3));
            // -------------------------------------------------------------------------------------
            // Nouveauté : Nombre de suppléments antepartum ----------------------------------------
            $BUF_record["nb_sup_ant"] = trim(substr($buffer, 132, 3));
            // -------------------------------------------------------------------------------------
            $BUF_record["nb_rdth"] = trim(substr($buffer, 135, 1));
            // top_valve_aortique : 1 si date sortie >=15/08/2012 + type autorisation UM 60 + acte pose, blanc sinon
            $BUF_record["top_valve_aortique"] = trim(substr($buffer, 136, 1));
            // type_generation_automatique: 0 = pas de génération automatique | 1 = FFM, ATU, SE | 2 = médecin salariés | 3 = dialyse
            $BUF_record["type_generation_automatique"] = trim(substr($buffer, 137, 1));
            $BUF_record["ghs_hors_innovation"] = trim(substr($buffer, 95, 4));
            $BUF_record["nb_seances_avant_sros"] = "00";
            $BUF_record["nb_sup_hyperbare"] = trim(substr($buffer, 150, 3));
            $BUF_record["type_prestation_prelevement_organe"] = trim(substr($buffer, 153, 1));
            $BUF_record["nb_sup_sra"] = "000";
            $BUF_record["nb_sup_rea"] = trim(substr($buffer, 154, 3));
            $BUF_record["nb_sup_si"] = trim(substr($buffer, 157, 3));
            $BUF_record["nb_sup_stf"] = trim(substr($buffer, 160, 3));
            $BUF_record["nb_sup_ssc"] = "000";
            $BUF_record["nb_sup_src"] = trim(substr($buffer, 163, 3));
            $BUF_record["nb_sup_nn1"] = trim(substr($buffer, 166, 3));
            $BUF_record["nb_sup_nn2"] = trim(substr($buffer, 169, 3));
            $BUF_record["nb_sup_nn3"] = trim(substr($buffer, 172, 3));
            $BUF_record["nb_sup_rep"] = trim(substr($buffer, 175, 3));
            $BUF_record["passage_lit_sp"] = trim(substr($buffer, 178, 1));
            $BUF_record["type_machine_rdth"] = trim(substr($buffer, 179, 1));
            $BUF_record["type_dosimetrie"] = trim(substr($buffer, 180, 1));
            $BUF_record["numero_innovation"] = trim(substr($buffer, 181, 15));
            $BUF_record["nombre_ivg_anterieures"] = "";
            $BUF_record["annee_ivg_precedente"] = "";
            $BUF_record["nombre_naissances_vivantes_anterieures"] = "";
            $BUF_record["nb_sup_sdc"] = trim(substr($buffer, 196, 1));
            $BUF_record["nb_faisceaux"] = "";
            $BUF_record["no_rum_dp"] = trim(substr($buffer, 209, 2));
            $BUF_record["diagnostic_principal"] = trim(substr($buffer, 211, 6));
            $BUF_record["diagnostic_relie"] = trim(substr($buffer, 217, 6));
            $BUF_record["nb_das"] = trim(substr($buffer, 223, 4));
            
            $BUF_aut_pgv_length = 2;

            //DRUIDE 2023
            $BUF_start = 262;
                
            //Version antèrieur à Druide
            $annee_import_fin = intval(substr($annee_mois_fin, 0, 4));
            $mois_import_fin = intval(substr($annee_mois_fin, -2));
            if ($annee_import_fin <= 2023 && $mois_import_fin < 3){
                $BUF_start = 247;
            }
            $BUF_record["ok"] = TRUE;
            break;
            case "214" :
                $BUF_record["BUF_offsets"] = $rsa_offsets_215;
                
                $BUF_record["no_rsa"] = trim(substr($buffer, 12, 10));
                $BUF_record["version_format"] = trim(substr($buffer, 22, 3));
                $BUF_record["numero_tarif"] = trim(substr($buffer, 25, 3));
                $BUF_record["version_groupage"] = trim(substr($buffer, 28, 2));
                $BUF_record["ghm"] = trim(substr($buffer, 30, 6));
                $BUF_record["code_retour"] = trim(substr($buffer, 36, 3));
                $BUF_record["version_groupage_genrsa"] = trim(substr($buffer, 39, 2));
                $BUF_record["ghm_genrsa"] = trim(substr($buffer, 41, 6));
                $BUF_record["code_retour_genrsa"] = trim(substr($buffer, 47, 3));
                $BUF_record["nombre_rum"] = trim(substr($buffer, 50, 2));
                $BUF_record["age_annees"] = trim(substr($buffer, 52, 3));
                $BUF_record["age_jours"] = trim(substr($buffer, 55, 3));
                $BUF_record["sexe"] = trim(substr($buffer, 58, 1));
                $BUF_record["mode_entree"] = trim(substr($buffer, 59, 1));
                $BUF_record["provenance"] = trim(substr($buffer, 60, 1));
                $BUF_record["mois_sortie"]= trim(substr($buffer, 61, 6));
                $BUF_record["mode_sortie"] = trim(substr($buffer, 67, 1));
                $BUF_record["destination"] = trim(substr($buffer, 68, 1));
                $BUF_record["type_sejour"] = trim(substr($buffer, 69, 1));
                $BUF_record["duree_sejour"] = trim(substr($buffer, 70, 4));
                $BUF_record["code_geographique"] = substr($buffer, 74, 5);
                $BUF_record["poids_entree"] = trim(substr($buffer, 79, 4));
                $BUF_record["age_gestationnel"] = "00";
                $BUF_record["nombre_seances"] = trim(substr($buffer, 83, 2));
                $BUF_record["igs2"] = trim(substr($buffer, 85, 3));
                $BUF_record["ghs_genrsa"] = trim(substr($buffer, 88, 4));
                $BUF_record["nb_exh"] = trim(substr($buffer, 92, 4));
                $BUF_record["nb_exb"] = trim(substr($buffer, 96, 1));
                
                $BUF_record["forfait_dialyse"] = trim(substr($buffer, 97, 4));
                $BUF_record["nb_sup_dialyse_1"] = trim(substr($buffer, 101, 3));
                $BUF_record["nb_sup_dialyse_2"] = trim(substr($buffer, 104, 3));
                $BUF_record["nb_sup_dialyse_3"] = trim(substr($buffer, 107, 3));
                $BUF_record["nb_sup_dialyse_4"] = trim(substr($buffer, 110, 3));
                $BUF_record["nb_seances_avant_sros"] = trim(substr($buffer, 115, 2));
                $BUF_record["nb_actes_9510"] = "000";
                $BUF_record["nb_actes_9511"] = "000";
                $BUF_record["nb_actes_9512"] = "000";
                $BUF_record["nb_actes_9515"] = "000";
                $BUF_record["nb_actes_9524"] = "000";
                $BUF_record["nb_actes_9622"] = "000";
                $BUF_record["nb_actes_9621"] = "000";
                $BUF_record["nb_actes_6523"] = "000";
                $BUF_record["nb_sup_hyperbare"] = trim(substr($buffer, 124, 3));
                $BUF_record["nb_sup_apherese"] = "000";
                $BUF_record["type_prestation_prelevement_organe"] = trim(substr($buffer, 127, 1));
                $BUF_record["nb_sup_sra"] = trim(substr($buffer, 128, 3));
                $BUF_record["nb_sup_rea"] = trim(substr($buffer, 131, 3));
                $BUF_record["nb_sup_si"] = trim(substr($buffer, 134, 3));
                $BUF_record["nb_sup_stf"] = trim(substr($buffer, 137, 3));
                $BUF_record["nb_sup_ssc"] = trim(substr($buffer, 140, 3));
                $BUF_record["nb_sup_src"] = trim(substr($buffer, 143, 3));
                $BUF_record["nb_sup_nn1"] = trim(substr($buffer, 146, 3));
                $BUF_record["nb_sup_nn2"] = trim(substr($buffer, 149, 3));
                $BUF_record["nb_sup_nn3"] = trim(substr($buffer, 152, 3));
                $BUF_record["nb_sup_rep"] = trim(substr($buffer, 155, 3));
                $BUF_record["passage_lit_sp"] = trim(substr($buffer, 158, 1));
                $BUF_record["no_rum_dp"] = "00";
                
                $BUF_record["ok"] = TRUE;
                
                break;
            case "215" :
                $BUF_record["BUF_offsets"] = $rsa_offsets_215;
            
                $BUF_record["no_rsa"] = trim(substr($buffer, 12, 10));
                $BUF_record["version_format"] = trim(substr($buffer, 22, 3));
                $BUF_record["numero_tarif"] = trim(substr($buffer, 25, 3));
                $BUF_record["version_groupage"] = trim(substr($buffer, 28, 2));
                $BUF_record["ghm"] = trim(substr($buffer, 30, 6));
                $BUF_record["code_retour"] = trim(substr($buffer, 36, 3));
                $BUF_record["version_groupage_genrsa"] = trim(substr($buffer, 39, 2));
                $BUF_record["ghm_genrsa"] = trim(substr($buffer, 41, 6));
                $BUF_record["code_retour_genrsa"] = trim(substr($buffer, 47, 3));
                $BUF_record["nombre_rum"] = trim(substr($buffer, 50, 2));
                $BUF_record["age_annees"] = trim(substr($buffer, 52, 3));
                $BUF_record["age_jours"] = trim(substr($buffer, 55, 3));
                $BUF_record["sexe"] = trim(substr($buffer, 58, 1));
                $BUF_record["mode_entree"] = trim(substr($buffer, 59, 1));
                $BUF_record["provenance"] = trim(substr($buffer, 60, 1));
                $BUF_record["mois_sortie"]= trim(substr($buffer, 61, 6));
                $BUF_record["mode_sortie"] = trim(substr($buffer, 67, 1));
                $BUF_record["destination"] = trim(substr($buffer, 68, 1));
                $BUF_record["type_sejour"] = trim(substr($buffer, 69, 1));
                $BUF_record["duree_sejour"] = trim(substr($buffer, 70, 4));
                $BUF_record["code_geographique"] = substr($buffer, 74, 5);
                $BUF_record["poids_entree"] = trim(substr($buffer, 79, 4));
                $BUF_record["age_gestationnel"] = trim(substr($buffer, 83, 2));
                $BUF_record["nombre_seances"] = trim(substr($buffer, 85, 2));
                $BUF_record["igs2"] = trim(substr($buffer, 87, 3));
                $BUF_record["ghs_genrsa"] = trim(substr($buffer, 90, 4));
                $BUF_record["nb_exh"] = trim(substr($buffer, 94, 4));
                $BUF_record["nb_exb"] = trim(substr($buffer, 98, 1));
                
                $BUF_record["forfait_dialyse"] = trim(substr($buffer, 99, 4));
                $BUF_record["nb_sup_dialyse_1"] = trim(substr($buffer, 103, 3));
                $BUF_record["nb_sup_dialyse_2"] = trim(substr($buffer, 106, 3));
                $BUF_record["nb_sup_dialyse_3"] = trim(substr($buffer, 109, 3));
                $BUF_record["nb_sup_dialyse_4"] = trim(substr($buffer, 112, 3));
                $BUF_record["nb_seances_avant_sros"] = trim(substr($buffer, 115, 2));
                $BUF_record["nb_actes_9510"] = trim(substr($buffer, 117, 3));
                $BUF_record["nb_actes_9511"] = trim(substr($buffer, 120, 3));
                $BUF_record["nb_actes_9512"] = trim(substr($buffer, 123, 3));
                $BUF_record["nb_actes_9515"] = trim(substr($buffer, 126, 3));
                $BUF_record["nb_actes_9524"] = trim(substr($buffer, 129, 3));
                $BUF_record["nb_actes_9622"] = "000";
                $BUF_record["nb_actes_9621"] = "000";
                $BUF_record["nb_actes_6523"] = "000";
                $BUF_record["nb_sup_hyperbare"] = trim(substr($buffer, 132, 3));
                $BUF_record["nb_sup_apherese"] = "000";
                $BUF_record["type_prestation_prelevement_organe"] = trim(substr($buffer, 135, 1));
                $BUF_record["nb_sup_sra"] = trim(substr($buffer, 136, 3));
                $BUF_record["nb_sup_rea"] = trim(substr($buffer, 139, 3));
                $BUF_record["nb_sup_si"] = trim(substr($buffer, 142, 3));
                $BUF_record["nb_sup_stf"] = trim(substr($buffer, 145, 3));
                $BUF_record["nb_sup_ssc"] = trim(substr($buffer, 148, 3));
                $BUF_record["nb_sup_src"] = trim(substr($buffer, 151, 3));
                $BUF_record["nb_sup_nn1"] = trim(substr($buffer, 154, 3));
                $BUF_record["nb_sup_nn2"] = trim(substr($buffer, 157, 3));
                $BUF_record["nb_sup_nn3"] = trim(substr($buffer, 160, 3));
                $BUF_record["nb_sup_rep"] = trim(substr($buffer, 163, 3));
                $BUF_record["passage_lit_sp"] = trim(substr($buffer, 166, 1));
                $BUF_record["no_rum_dp"] = trim(substr($buffer, 167, 2));
                
                $BUF_record["ok"] = TRUE;
                
                break;
            case "216" :
                $BUF_record["BUF_offsets"] = $rsa_offsets_215;
                
                $BUF_record["no_rsa"] = trim(substr($buffer, 12, 10));
                $BUF_record["version_format"] = trim(substr($buffer, 22, 3));
                $BUF_record["numero_tarif"] = trim(substr($buffer, 25, 3));
                $BUF_record["version_groupage"] = trim(substr($buffer, 28, 2));
                $BUF_record["ghm"] = trim(substr($buffer, 30, 6));
                $BUF_record["code_retour"] = trim(substr($buffer, 36, 3));
                $BUF_record["version_groupage_genrsa"] = trim(substr($buffer, 39, 2));
                $BUF_record["ghm_genrsa"] = trim(substr($buffer, 41, 6));
                $BUF_record["code_retour_genrsa"] = trim(substr($buffer, 47, 3));
                $BUF_record["nombre_rum"] = trim(substr($buffer, 50, 2));
                $BUF_record["age_annees"] = trim(substr($buffer, 52, 3));
                $BUF_record["age_jours"] = trim(substr($buffer, 55, 3));
                $BUF_record["sexe"] = trim(substr($buffer, 58, 1));
                $BUF_record["mode_entree"] = trim(substr($buffer, 59, 1));
                $BUF_record["provenance"] = trim(substr($buffer, 60, 1));
                $BUF_record["mois_sortie"]= trim(substr($buffer, 61, 6));
                $BUF_record["mode_sortie"] = trim(substr($buffer, 67, 1));
                $BUF_record["destination"] = trim(substr($buffer, 68, 1));
                $BUF_record["type_sejour"] = trim(substr($buffer, 69, 1));
                $BUF_record["duree_sejour"] = trim(substr($buffer, 70, 4));
                $BUF_record["code_geographique"] = substr($buffer, 74, 5);
                $BUF_record["poids_entree"] = trim(substr($buffer, 79, 4));
                $BUF_record["age_gestationnel"] = trim(substr($buffer, 83, 2));
                $BUF_record["nombre_seances"] = trim(substr($buffer, 85, 2));
                $BUF_record["igs2"] = trim(substr($buffer, 87, 3));
                $BUF_record["ghs_genrsa"] = trim(substr($buffer, 90, 4));
                
                // ???
                $BUF_record["nb_exh"] = trim(substr($buffer, 94, 4));
                $BUF_record["nb_exb"] = trim(substr($buffer, 99, 3));
                
                $BUF_record["forfait_dialyse"] = trim(substr($buffer, 102, 4));
                $BUF_record["top_uhcd"] = trim(substr($buffer, 106, 1));
                $BUF_record["nb_sup_dialyse_1"] = trim(substr($buffer, 108, 3));
                $BUF_record["nb_sup_dialyse_2"] = trim(substr($buffer, 111, 3));
                $BUF_record["nb_sup_dialyse_3"] = trim(substr($buffer, 114, 3));
                $BUF_record["nb_sup_dialyse_4"] = trim(substr($buffer, 117, 3));
                $BUF_record["nb_seances_avant_sros"] = "00";
                $BUF_record["nb_actes_9510"] = trim(substr($buffer, 120, 3));
                $BUF_record["nb_actes_9511"] = trim(substr($buffer, 123, 3));
                $BUF_record["nb_actes_9512"] = trim(substr($buffer, 126, 3));
                $BUF_record["nb_actes_9515"] = trim(substr($buffer, 129, 3));
                $BUF_record["nb_actes_9524"] = trim(substr($buffer, 132, 3));
                $BUF_record["nb_actes_9622"] = "000";
                $BUF_record["nb_actes_6523"] = trim(substr($buffer, 135, 3));
                $BUF_record["nb_actes_9621"] = trim(substr($buffer, 138, 3));
                $BUF_record["nb_sup_apherese"] = trim(substr($buffer, 141, 3));
                $BUF_record["nb_sup_hyperbare"] = trim(substr($buffer, 167, 3));
                
                $BUF_record["type_prestation_prelevement_organe"] = trim(substr($buffer, 170, 1));

                $BUF_record["nb_sup_sra"] = "000";
                $BUF_record["nb_sup_rea"] = trim(substr($buffer, 171, 3));
                $BUF_record["nb_sup_si"] = trim(substr($buffer, 174, 3));
                $BUF_record["nb_sup_stf"] = trim(substr($buffer, 177, 3));
                $BUF_record["nb_sup_ssc"] = "000";
                $BUF_record["nb_sup_src"] = trim(substr($buffer, 180, 3));
                $BUF_record["nb_sup_nn1"] = trim(substr($buffer, 183, 3));
                $BUF_record["nb_sup_nn2"] = trim(substr($buffer, 186, 3));
                $BUF_record["nb_sup_nn3"] = trim(substr($buffer, 189, 3));
                $BUF_record["nb_sup_rep"] = trim(substr($buffer, 192, 3));
                $BUF_record["passage_lit_sp"] = trim(substr($buffer, 195, 1));
                $BUF_record["no_rum_dp"] = trim(substr($buffer, 198, 2));
                
                $BUF_record["ok"] = TRUE;
                
                break;
            case "217" :
                $BUF_record["BUF_offsets"] = $rsa_offsets_215;
            
                $BUF_record["no_rsa"] = trim(substr($buffer, 12, 10));
                $BUF_record["version_format"] = trim(substr($buffer, 22, 3));
                $BUF_record["numero_tarif"] = trim(substr($buffer, 25, 3));
                $BUF_record["version_groupage"] = trim(substr($buffer, 28, 2));
                $BUF_record["ghm"] = trim(substr($buffer, 30, 6));
                $BUF_record["code_retour"] = trim(substr($buffer, 36, 3));
                $BUF_record["version_groupage_genrsa"] = trim(substr($buffer, 39, 2));
                $BUF_record["ghm_genrsa"] = trim(substr($buffer, 41, 6));
                $BUF_record["code_retour_genrsa"] = trim(substr($buffer, 47, 3));
                $BUF_record["nombre_rum"] = trim(substr($buffer, 50, 2));
                $BUF_record["age_annees"] = trim(substr($buffer, 52, 3));
                $BUF_record["age_jours"] = trim(substr($buffer, 55, 3));
                $BUF_record["sexe"] = trim(substr($buffer, 58, 1));
                $BUF_record["mode_entree"] = trim(substr($buffer, 59, 1));
                $BUF_record["provenance"] = trim(substr($buffer, 60, 1));
                $BUF_record["mois_sortie"]= trim(substr($buffer, 61, 6));
                $BUF_record["mode_sortie"] = trim(substr($buffer, 67, 1));
                $BUF_record["destination"] = trim(substr($buffer, 68, 1));
                $BUF_record["type_sejour"] = trim(substr($buffer, 69, 1));
                $BUF_record["duree_sejour"] = trim(substr($buffer, 70, 4));
                $BUF_record["code_geographique"] = substr($buffer, 74, 5);
                $BUF_record["poids_entree"] = trim(substr($buffer, 79, 4));
                $BUF_record["age_gestationnel"] = trim(substr($buffer, 83, 2));
                $BUF_record["nombre_seances"] = trim(substr($buffer, 85, 2));
                $BUF_record["igs2"] = "000";
                $BUF_record["ghs_genrsa"] = trim(substr($buffer, 87, 4));
                
                // ???
                $BUF_record["nb_exh"] = trim(substr($buffer, 91, 4));
                $BUF_record["nb_exb"] = trim(substr($buffer, 96, 3));
                
                $BUF_record["forfait_dialyse"] = trim(substr($buffer, 99, 4));
                $BUF_record["top_uhcd"] = trim(substr($buffer, 103, 1));
                $BUF_record["nb_sup_dialyse_1"] = trim(substr($buffer, 105, 3));
                $BUF_record["nb_sup_dialyse_2"] = trim(substr($buffer, 108, 3));
                $BUF_record["nb_sup_dialyse_3"] = trim(substr($buffer, 111, 3));
                $BUF_record["nb_sup_dialyse_4"] = trim(substr($buffer, 114, 3));
                $BUF_record["nb_seances_avant_sros"] = "00";
                $BUF_record["nb_actes_9510"] = trim(substr($buffer, 117, 3)); // 9610
                $BUF_record["nb_actes_9511"] = trim(substr($buffer, 120, 3)); // 9611
                $BUF_record["nb_actes_9512"] = trim(substr($buffer, 123, 3)); // 9612
                $BUF_record["nb_actes_9515"] = trim(substr($buffer, 126, 3)); // 9619
                $BUF_record["nb_actes_9524"] = trim(substr($buffer, 129, 3)); // 9620
                $BUF_record["nb_actes_6523"] = trim(substr($buffer, 132, 3));
                $BUF_record["nb_actes_9621"] = trim(substr($buffer, 135, 3));
                $BUF_record["nb_sup_apherese"] = trim(substr($buffer, 138, 3)); // 9615
                $BUF_record["nb_actes_9622"] = trim(substr($buffer, 141, 3));
                
                $BUF_record["nb_sup_hyperbare"] = trim(substr($buffer, 166, 3));
                
                $BUF_record["type_prestation_prelevement_organe"] = trim(substr($buffer, 170, 1));

                $BUF_record["nb_sup_sra"] = "000";
                $BUF_record["nb_sup_rea"] = trim(substr($buffer, 170, 3));
                $BUF_record["nb_sup_si"] = trim(substr($buffer, 173, 3));
                $BUF_record["nb_sup_stf"] = trim(substr($buffer, 176, 3));
                $BUF_record["nb_sup_ssc"] = "000";
                $BUF_record["nb_sup_src"] = trim(substr($buffer, 179, 3));
                $BUF_record["nb_sup_nn1"] = trim(substr($buffer, 182, 3));
                $BUF_record["nb_sup_nn2"] = trim(substr($buffer, 185, 3));
                $BUF_record["nb_sup_nn3"] = trim(substr($buffer, 188, 3));
                $BUF_record["nb_sup_rep"] = trim(substr($buffer, 191, 3));
                $BUF_record["passage_lit_sp"] = trim(substr($buffer, 194, 1));
                $BUF_record["nb_faisceaux"] = trim(substr($buffer, 197, 1));
                $BUF_record["no_rum_dp"] = trim(substr($buffer, 198, 2));
                
                $BUF_record["ok"] = TRUE;
                
                break;
            case "218" :
                $BUF_record["BUF_offsets"] = $rsa_offsets_215;
                $BUF_record["no_rsa"] = trim(substr($buffer, 12, 10));
                $BUF_record["version_format"] = trim(substr($buffer, 22, 3));
                $BUF_record["numero_tarif"] = trim(substr($buffer, 25, 3));
                $BUF_record["version_groupage"] = trim(substr($buffer, 28, 2));
                $BUF_record["ghm"] = trim(substr($buffer, 30, 6));
                $BUF_record["code_retour"] = trim(substr($buffer, 36, 3));
                $BUF_record["version_groupage_genrsa"] = trim(substr($buffer, 39, 2));
                $BUF_record["ghm_genrsa"] = trim(substr($buffer, 41, 6));
                $BUF_record["code_retour_genrsa"] = trim(substr($buffer, 47, 3));
                $BUF_record["nombre_rum"] = trim(substr($buffer, 50, 2));
                $BUF_record["age_annees"] = trim(substr($buffer, 52, 3));
                $BUF_record["age_jours"] = trim(substr($buffer, 55, 3));
                $BUF_record["sexe"] = trim(substr($buffer, 58, 1));
                $BUF_record["mode_entree"] = trim(substr($buffer, 59, 1));
                $BUF_record["provenance"] = trim(substr($buffer, 60, 1));
                $BUF_record["mois_sortie"]= trim(substr($buffer, 61, 6));
                $BUF_record["mode_sortie"] = trim(substr($buffer, 67, 1));
                $BUF_record["destination"] = trim(substr($buffer, 68, 1));
                $BUF_record["type_sejour"] = trim(substr($buffer, 69, 1));
                $BUF_record["duree_sejour"] = trim(substr($buffer, 70, 4));
                $BUF_record["code_geographique"] = substr($buffer, 74, 5);
                $BUF_record["poids_entree"] = trim(substr($buffer, 79, 4));
                $BUF_record["age_gestationnel"] = trim(substr($buffer, 83, 2));
                $BUF_record["delai_dernieres_regles"] = trim(substr($buffer, 85, 3));
                $BUF_record["nombre_seances"] = trim(substr($buffer, 88, 2));
                $BUF_record["igs2"] = "000";
                $BUF_record["ghs_genrsa"] = trim(substr($buffer, 90, 4));
                $BUF_record["nb_exh"] = trim(substr($buffer, 94, 4));
                $BUF_record["nb_exb"] = trim(substr($buffer, 99, 3)); 
                $BUF_record["forfait_dialyse"] = trim(substr($buffer, 102, 4));
                $BUF_record["top_uhcd"] = trim(substr($buffer, 106, 1));
                $BUF_record["confirmation_codage"] = trim(substr($buffer, 107, 1));
                $BUF_record["nb_sup_dialyse_1"] = trim(substr($buffer, 108, 3));
                $BUF_record["nb_sup_dialyse_2"] = trim(substr($buffer, 111, 3));
                $BUF_record["nb_sup_dialyse_3"] = trim(substr($buffer, 114, 3));
                $BUF_record["nb_sup_dialyse_4"] = trim(substr($buffer, 117, 3));
                $BUF_record["nb_sup_apherese"] = trim(substr($buffer, 120, 3));
                $BUF_record["nb_rdth"] = trim(substr($buffer, 123, 1));
                $BUF_record["nb_seances_avant_sros"] = "00";
                $BUF_record["nb_sup_hyperbare"] = trim(substr($buffer, 146, 3));
                $BUF_record["type_prestation_prelevement_organe"] = trim(substr($buffer, 149, 1));
                $BUF_record["nb_sup_sra"] = "000";
                $BUF_record["nb_sup_rea"] = trim(substr($buffer, 150, 3));
                $BUF_record["nb_sup_si"] = trim(substr($buffer, 153, 3));
                $BUF_record["nb_sup_stf"] = trim(substr($buffer, 156, 3));
                $BUF_record["nb_sup_ssc"] = "000";
                $BUF_record["nb_sup_src"] = trim(substr($buffer, 159, 3));
                $BUF_record["nb_sup_nn1"] = trim(substr($buffer, 162, 3));
                $BUF_record["nb_sup_nn2"] = trim(substr($buffer, 165, 3));
                $BUF_record["nb_sup_nn3"] = trim(substr($buffer, 168, 3));
                $BUF_record["nb_sup_rep"] = trim(substr($buffer, 171, 3));
                $BUF_record["passage_lit_sp"] = trim(substr($buffer, 174, 1));
                $BUF_record["type_machine_rdth"] = trim(substr($buffer, 175, 1));
                $BUF_record["type_dosimetrie"] = trim(substr($buffer, 176, 1));
                $BUF_record["numero_innovation"] = trim(substr($buffer, 177, 15));
                $BUF_record["nb_faisceaux"] = trim(substr($buffer, 192, 1));
                $BUF_record["no_rum_dp"] = trim(substr($buffer, 193, 2));
                
                $BUF_start = 216;
                $BUF_record["ok"] = TRUE;
                
                break;
            case "219" :
                // Applicable à compter de M01 2012
            case "220" :
                // Applicable à compter de M01 2013
            case "221" :
                // Applicable à compter de M01 2014
                $BUF_record["BUF_offsets"] = $rsa_offsets_215;
                $BUF_record["no_rsa"] = trim(substr($buffer, 12, 10));
                $BUF_record["version_format"] = trim(substr($buffer, 22, 3));
                $BUF_record["numero_tarif"] = trim(substr($buffer, 25, 3));
                $BUF_record["version_groupage"] = trim(substr($buffer, 28, 2));
                $BUF_record["ghm"] = trim(substr($buffer, 30, 6));
                $BUF_record["code_retour"] = trim(substr($buffer, 36, 3));
                $BUF_record["version_groupage_genrsa"] = trim(substr($buffer, 39, 2));
                $BUF_record["ghm_genrsa"] = trim(substr($buffer, 41, 6));
                $BUF_record["code_retour_genrsa"] = trim(substr($buffer, 47, 3));
                $BUF_record["nombre_rum"] = trim(substr($buffer, 50, 2));
                $BUF_record["age_annees"] = trim(substr($buffer, 52, 3));
                $BUF_record["age_jours"] = trim(substr($buffer, 55, 3));
                $BUF_record["sexe"] = trim(substr($buffer, 58, 1));
                $BUF_record["mode_entree"] = trim(substr($buffer, 59, 1));
                $BUF_record["provenance"] = trim(substr($buffer, 60, 1));
                $BUF_record["mois_sortie"]= trim(substr($buffer, 61, 6));
                $BUF_record["mode_sortie"] = trim(substr($buffer, 67, 1));
                $BUF_record["destination"] = trim(substr($buffer, 68, 1));
                $BUF_record["type_sejour"] = trim(substr($buffer, 69, 1));
                $BUF_record["duree_sejour"] = trim(substr($buffer, 70, 4));
                $BUF_record["code_geographique"] = substr($buffer, 74, 5);
                $BUF_record["poids_entree"] = trim(substr($buffer, 79, 4));
                $BUF_record["age_gestationnel"] = trim(substr($buffer, 83, 2));
                $BUF_record["delai_dernieres_regles"] = trim(substr($buffer, 85, 3));
                $BUF_record["nombre_seances"] = trim(substr($buffer, 88, 2));
                $BUF_record["igs2"] = "000";
                $BUF_record["ghs_genrsa"] = trim(substr($buffer, 90, 4));
                $BUF_record["nb_exh"] = trim(substr($buffer, 94, 4));
                $BUF_record["nb_exb"] = trim(substr($buffer, 99, 3)); 
                $BUF_record["forfait_dialyse"] = trim(substr($buffer, 102, 4));
                $BUF_record["top_uhcd"] = trim(substr($buffer, 106, 1));
                $BUF_record["confirmation_codage"] = trim(substr($buffer, 107, 1));
                // Nouveauté non exploitée : Nombre d'autorisations d'unités médicales à portée globale valides (Nb_AutPGV)
                $BUF_record["nb_aut_pgv"] = trim(substr($buffer, 108, 1));
                // -------------------------------------------------------------------------------------
                $BUF_record["nb_sup_dialyse_1"] = trim(substr($buffer, 109, 3));
                $BUF_record["nb_sup_dialyse_2"] = trim(substr($buffer, 112, 3));
                $BUF_record["nb_sup_dialyse_3"] = trim(substr($buffer, 115, 3));
                $BUF_record["nb_sup_dialyse_4"] = trim(substr($buffer, 118, 3));
                $BUF_record["nb_sup_apherese"] = trim(substr($buffer, 121, 3));
                // Nouveauté : Nombre de suppléments radiothérapie pédiatrique -------------------------
                $BUF_record["nb_sup_rap"] = trim(substr($buffer, 124, 3));
                // -------------------------------------------------------------------------------------
                // Nouveauté : Nombre de suppléments antepartum ----------------------------------------
                $BUF_record["nb_sup_ant"] = trim(substr($buffer, 127, 3));
                // -------------------------------------------------------------------------------------
                $BUF_record["nb_rdth"] = trim(substr($buffer, 130, 1));
                $BUF_record["nb_seances_avant_sros"] = "00";
                $BUF_record["nb_sup_hyperbare"] = trim(substr($buffer, 153, 3));
                $BUF_record["type_prestation_prelevement_organe"] = trim(substr($buffer, 156, 1));
                $BUF_record["nb_sup_sra"] = "000";
                $BUF_record["nb_sup_rea"] = trim(substr($buffer, 157, 3));
                $BUF_record["nb_sup_si"] = trim(substr($buffer, 160, 3));
                $BUF_record["nb_sup_stf"] = trim(substr($buffer, 163, 3));
                $BUF_record["nb_sup_ssc"] = "000";
                $BUF_record["nb_sup_src"] = trim(substr($buffer, 166, 3));
                $BUF_record["nb_sup_nn1"] = trim(substr($buffer, 169, 3));
                $BUF_record["nb_sup_nn2"] = trim(substr($buffer, 172, 3));
                $BUF_record["nb_sup_nn3"] = trim(substr($buffer, 175, 3));
                $BUF_record["nb_sup_rep"] = trim(substr($buffer, 178, 3));
                $BUF_record["passage_lit_sp"] = trim(substr($buffer, 181, 1));
                $BUF_record["type_machine_rdth"] = trim(substr($buffer, 182, 1));
                $BUF_record["type_dosimetrie"] = trim(substr($buffer, 183, 1));
                $BUF_record["numero_innovation"] = trim(substr($buffer, 184, 15));
                $BUF_record["nb_faisceaux"] = trim(substr($buffer, 199, 1));
                $BUF_record["no_rum_dp"] = trim(substr($buffer, 200, 2));
                
                $BUF_aut_pgv_length = 2;
                
                $BUF_start = 223;
                $BUF_record["ok"] = TRUE;
                
                break;      
            case "222" :
                // 222 - Applicable à compter de M01 2015
                $BUF_record["BUF_offsets"] = $rsa_offsets_222;
                $BUF_record["no_rsa"] = trim(substr($buffer, 12, 10));
                $BUF_record["version_format"] = trim(substr($buffer, 22, 3));
                $BUF_record["numero_tarif"] = trim(substr($buffer, 25, 3));
                $BUF_record["version_groupage"] = trim(substr($buffer, 28, 2));
                $BUF_record["ghm"] = trim(substr($buffer, 30, 6));
                $BUF_record["code_retour"] = trim(substr($buffer, 36, 3));
                $BUF_record["version_groupage_genrsa"] = trim(substr($buffer, 39, 2));
                $BUF_record["ghm_genrsa"] = trim(substr($buffer, 41, 6));
                $BUF_record["code_retour_genrsa"] = trim(substr($buffer, 47, 3));
                $BUF_record["nombre_rum"] = trim(substr($buffer, 50, 2));
                $BUF_record["age_annees"] = trim(substr($buffer, 52, 3));
                $BUF_record["age_jours"] = trim(substr($buffer, 55, 3));
                $BUF_record["sexe"] = trim(substr($buffer, 58, 1));
                $BUF_record["mode_entree"] = trim(substr($buffer, 59, 1));
                $BUF_record["provenance"] = trim(substr($buffer, 60, 1));
                $BUF_record["mois_sortie"]= trim(substr($buffer, 61, 6));
                $BUF_record["mode_sortie"] = trim(substr($buffer, 67, 1));
                $BUF_record["destination"] = trim(substr($buffer, 68, 1));
                $BUF_record["type_sejour"] = trim(substr($buffer, 69, 1));
                $BUF_record["duree_sejour"] = trim(substr($buffer, 70, 4));
                $BUF_record["code_geographique"] = substr($buffer, 74, 5);
                $BUF_record["poids_entree"] = trim(substr($buffer, 79, 4));
                $BUF_record["age_gestationnel"] = trim(substr($buffer, 83, 2));
                $BUF_record["delai_dernieres_regles"] = trim(substr($buffer, 85, 3));
                $BUF_record["nombre_seances"] = trim(substr($buffer, 88, 2));
                $BUF_record["igs2"] = "000";
                $BUF_record["ghs_genrsa"] = trim(substr($buffer, 90, 4));
                $BUF_record["nb_exh"] = trim(substr($buffer, 94, 4));
                $BUF_record["type_exb"] = trim(substr($buffer, 98, 1));
                $BUF_record["nb_exb"] = trim(substr($buffer, 99, 3)); 
                $BUF_record["forfait_dialyse"] = "";
                $BUF_record["top_uhcd"] = trim(substr($buffer, 105, 1));
                // top_ghs_minore : 0 = non | 1 = oui
                $BUF_record["top_ghs_minore"] = trim(substr($buffer, 106, 1));
                $BUF_record["confirmation_codage"] = trim(substr($buffer, 107, 1));
                // Nouveauté non exploitée : Nombre d'autorisations d'unités médicales à portée globale valides (Nb_AutPGV)
                $BUF_record["nb_aut_pgv"] = trim(substr($buffer, 108, 1));
                // -------------------------------------------------------------------------------------
                $BUF_record["nb_sup_dialyse_1"] = trim(substr($buffer, 109, 3));
                $BUF_record["nb_sup_dialyse_2"] = trim(substr($buffer, 112, 3));
                $BUF_record["nb_sup_dialyse_3"] = trim(substr($buffer, 115, 3));
                $BUF_record["nb_sup_dialyse_4"] = trim(substr($buffer, 118, 3));
                $BUF_record["nb_sup_apherese"] = trim(substr($buffer, 121, 3));
                // Nouveauté : Nombre de suppléments radiothérapie pédiatrique -------------------------
                $BUF_record["nb_sup_rap"] = trim(substr($buffer, 124, 3));
                // -------------------------------------------------------------------------------------
                // Nouveauté : Nombre de suppléments antepartum ----------------------------------------
                $BUF_record["nb_sup_ant"] = trim(substr($buffer, 127, 3));
                // -------------------------------------------------------------------------------------
                $BUF_record["nb_rdth"] = trim(substr($buffer, 130, 1));
                // top_valve_aortique : 1 si date sortie >=15/08/2012 + type autorisation UM 60 + acte pose, blanc sinon
                $BUF_record["top_valve_aortique"] = trim(substr($buffer, 131, 1));
                // type_generation_automatique: 0 = pas de génération automatique | 1 = FFM, ATU, SE | 2 = médecin salariés | 3 = dialyse
                $BUF_record["type_generation_automatique"] = trim(substr($buffer, 132, 1));
                $BUF_record["nb_seances_avant_sros"] = "00";
                $BUF_record["nb_sup_hyperbare"] = trim(substr($buffer, 145, 3));
                $BUF_record["type_prestation_prelevement_organe"] = trim(substr($buffer, 148, 1));
                $BUF_record["nb_sup_sra"] = "000";
                $BUF_record["nb_sup_rea"] = trim(substr($buffer, 149, 3));
                $BUF_record["nb_sup_si"] = trim(substr($buffer, 152, 3));
                $BUF_record["nb_sup_stf"] = trim(substr($buffer, 155, 3));
                $BUF_record["nb_sup_ssc"] = "000";
                $BUF_record["nb_sup_src"] = trim(substr($buffer, 158, 3));
                $BUF_record["nb_sup_nn1"] = trim(substr($buffer, 161, 3));
                $BUF_record["nb_sup_nn2"] = trim(substr($buffer, 164, 3));
                $BUF_record["nb_sup_nn3"] = trim(substr($buffer, 167, 3));
                $BUF_record["nb_sup_rep"] = trim(substr($buffer, 170, 3));
                $BUF_record["passage_lit_sp"] = trim(substr($buffer, 173, 1));
                $BUF_record["type_machine_rdth"] = trim(substr($buffer, 174, 1));
                $BUF_record["type_dosimetrie"] = trim(substr($buffer, 175, 1));
                $BUF_record["numero_innovation"] = trim(substr($buffer, 176, 15));
                $BUF_record["nombre_ivg_anterieures"] = trim(substr($buffer, 191, 2));
                $BUF_record["annee_ivg_precedente"] = trim(substr($buffer, 193, 4));
                $BUF_record["nombre_naissances_vivantes_anterieures"] = trim(substr($buffer, 197, 2));
                $BUF_record["nb_faisceaux"] = "";
                $BUF_record["no_rum_dp"] = trim(substr($buffer, 200, 2));
                $BUF_record["nb_sup_sdc"] = "";
                $BUF_aut_pgv_length = 2;
                
                $BUF_start = 223;
                $BUF_record["ok"] = TRUE;
                break;      
            case "223" :
                // 223 - Applicable à compter de M01 2016
                $BUF_record["BUF_offsets"] = $rsa_offsets_223;
                $BUF_record["no_rsa"] = trim(substr($buffer, 12, 10));
                $BUF_record["version_format"] = trim(substr($buffer, 22, 3));
                $BUF_record["numero_tarif"] = trim(substr($buffer, 25, 3));
                $BUF_record["version_groupage"] = trim(substr($buffer, 28, 2));
                $BUF_record["ghm"] = trim(substr($buffer, 30, 6));
                $BUF_record["code_retour"] = trim(substr($buffer, 36, 3));
                $BUF_record["version_groupage_genrsa"] = trim(substr($buffer, 39, 2));
                $BUF_record["ghm_genrsa"] = trim(substr($buffer, 41, 6));
                $BUF_record["code_retour_genrsa"] = trim(substr($buffer, 47, 3));
                $BUF_record["nombre_rum"] = trim(substr($buffer, 50, 2));
                $BUF_record["age_annees"] = trim(substr($buffer, 52, 3));
                $BUF_record["age_jours"] = trim(substr($buffer, 55, 3));
                $BUF_record["sexe"] = trim(substr($buffer, 58, 1));
                $BUF_record["mode_entree"] = trim(substr($buffer, 59, 1));
                $BUF_record["provenance"] = trim(substr($buffer, 60, 1));
                $BUF_record["mois_sortie"]= trim(substr($buffer, 61, 6));
                $BUF_record["mode_sortie"] = trim(substr($buffer, 67, 1));
                $BUF_record["destination"] = trim(substr($buffer, 68, 1));
                $BUF_record["type_sejour"] = trim(substr($buffer, 69, 1));
                $BUF_record["duree_sejour"] = trim(substr($buffer, 70, 4));
                $BUF_record["code_geographique"] = substr($buffer, 74, 5);
                $BUF_record["poids_entree"] = trim(substr($buffer, 79, 4));
                $BUF_record["age_gestationnel"] = trim(substr($buffer, 83, 2));
                $BUF_record["delai_dernieres_regles"] = trim(substr($buffer, 85, 3));
                $BUF_record["nombre_seances"] = trim(substr($buffer, 88, 2));
                $BUF_record["igs2"] = "000";
                $BUF_record["ghs_genrsa"] = trim(substr($buffer, 90, 4));
                $BUF_record["nb_exh"] = trim(substr($buffer, 94, 4));
                $BUF_record["type_exb"] = trim(substr($buffer, 98, 1));
                $BUF_record["nb_exb"] = trim(substr($buffer, 99, 3)); 
                $BUF_record["forfait_dialyse"] = "";

                // Nouveauté non exploitée : Top Admission Maison de Naissance 0:NON / 1:OUI
                $BUF_record["top_adm_maison_naissance"] = trim(substr($buffer, 102, 1));
                // Nouveauté non exploitée : Top Radiation partielle Avastin 0:NON / 1:OUI
                $BUF_record["top_radiation_part_avastin"] = trim(substr($buffer, 103, 1));
                // Nouveauté non exploitée : Top Radiation partielle Alimta 0:NON / 1:OUI
                $BUF_record["top_radiation_partielle_alimta"] = trim(substr($buffer, 104, 1));

                $BUF_record["top_uhcd"] = trim(substr($buffer, 105, 1));
                // top_ghs_minore : 0 = non | 1 = oui
                $BUF_record["top_ghs_minore"] = trim(substr($buffer, 106, 1));
                $BUF_record["confirmation_codage"] = trim(substr($buffer, 107, 1));
                // Nouveauté non exploitée : Nombre d'autorisations d'unités médicales à portée globale valides (Nb_AutPGV)
                $BUF_record["nb_aut_pgv"] = trim(substr($buffer, 108, 1));
                // -------------------------------------------------------------------------------------
                $BUF_record["nb_sup_dialyse_1"] = trim(substr($buffer, 109, 3));
                $BUF_record["nb_sup_dialyse_2"] = trim(substr($buffer, 112, 3));
                $BUF_record["nb_sup_dialyse_3"] = trim(substr($buffer, 115, 3));
                $BUF_record["nb_sup_dialyse_4"] = trim(substr($buffer, 118, 3));
                $BUF_record["nb_sup_apherese"] = trim(substr($buffer, 121, 3));
                // Nouveauté : Nombre de suppléments radiothérapie pédiatrique -------------------------
                $BUF_record["nb_sup_rap"] = trim(substr($buffer, 124, 3));
                // -------------------------------------------------------------------------------------
                // Nouveauté : Nombre de suppléments antepartum ----------------------------------------
                $BUF_record["nb_sup_ant"] = trim(substr($buffer, 127, 3));
                // -------------------------------------------------------------------------------------
                $BUF_record["nb_rdth"] = trim(substr($buffer, 130, 1));
                // top_valve_aortique : 1 si date sortie >=15/08/2012 + type autorisation UM 60 + acte pose, blanc sinon
                $BUF_record["top_valve_aortique"] = trim(substr($buffer, 131, 1));
                // type_generation_automatique: 0 = pas de génération automatique | 1 = FFM, ATU, SE | 2 = médecin salariés | 3 = dialyse
                $BUF_record["type_generation_automatique"] = trim(substr($buffer, 132, 1));
                $BUF_record["nb_seances_avant_sros"] = "00";
                $BUF_record["nb_sup_hyperbare"] = trim(substr($buffer, 145, 3));
                $BUF_record["type_prestation_prelevement_organe"] = trim(substr($buffer, 148, 1));
                $BUF_record["nb_sup_sra"] = "000";
                $BUF_record["nb_sup_rea"] = trim(substr($buffer, 149, 3));
                $BUF_record["nb_sup_si"] = trim(substr($buffer, 152, 3));
                $BUF_record["nb_sup_stf"] = trim(substr($buffer, 155, 3));
                $BUF_record["nb_sup_ssc"] = "000";
                $BUF_record["nb_sup_src"] = trim(substr($buffer, 158, 3));
                $BUF_record["nb_sup_nn1"] = trim(substr($buffer, 161, 3));
                $BUF_record["nb_sup_nn2"] = trim(substr($buffer, 164, 3));
                $BUF_record["nb_sup_nn3"] = trim(substr($buffer, 167, 3));
                $BUF_record["nb_sup_rep"] = trim(substr($buffer, 170, 3));
                $BUF_record["passage_lit_sp"] = trim(substr($buffer, 173, 1));
                $BUF_record["type_machine_rdth"] = trim(substr($buffer, 174, 1));
                $BUF_record["type_dosimetrie"] = trim(substr($buffer, 175, 1));
                $BUF_record["numero_innovation"] = trim(substr($buffer, 176, 15));
                $BUF_record["nombre_ivg_anterieures"] = trim(substr($buffer, 191, 2));
                $BUF_record["annee_ivg_precedente"] = trim(substr($buffer, 193, 4));
                $BUF_record["nombre_naissances_vivantes_anterieures"] = trim(substr($buffer, 197, 2));
                $BUF_record["nb_faisceaux"] = "";
                $BUF_record["no_rum_dp"] = trim(substr($buffer, 200, 2));
                $BUF_record["nb_sup_sdc"] = "";
                $BUF_aut_pgv_length = 2;
                
                $BUF_start = 238;
                $BUF_record["ok"] = TRUE;
                break;
			case "224" :
			case "225" :
				// 224 - Applicable à compter de M01 2018
                $BUF_record["BUF_offsets"] = $rsa_offsets_223;
                $BUF_record["no_rsa"] = trim(substr($buffer, 12, 10));
                $BUF_record["version_format"] = trim(substr($buffer, 22, 3));
                $BUF_record["numero_tarif"] = trim(substr($buffer, 25, 3));
                $BUF_record["version_groupage"] = trim(substr($buffer, 28, 2));
                $BUF_record["ghm"] = trim(substr($buffer, 30, 6));
                $BUF_record["code_retour"] = trim(substr($buffer, 36, 3));
                $BUF_record["version_groupage_genrsa"] = trim(substr($buffer, 39, 2));
                $BUF_record["ghm_genrsa"] = trim(substr($buffer, 41, 6));
                $BUF_record["code_retour_genrsa"] = trim(substr($buffer, 47, 3));
                $BUF_record["nombre_rum"] = trim(substr($buffer, 50, 2));
                $BUF_record["age_annees"] = trim(substr($buffer, 52, 3));
                $BUF_record["age_jours"] = trim(substr($buffer, 55, 3));
                $BUF_record["sexe"] = trim(substr($buffer, 58, 1));
                $BUF_record["mode_entree"] = trim(substr($buffer, 59, 1));
                $BUF_record["provenance"] = trim(substr($buffer, 60, 1));
                $BUF_record["mois_sortie"]= trim(substr($buffer, 61, 6));
                $BUF_record["mode_sortie"] = trim(substr($buffer, 67, 1));
                $BUF_record["destination"] = trim(substr($buffer, 68, 1));
                $BUF_record["type_sejour"] = trim(substr($buffer, 69, 1));
                $BUF_record["duree_sejour"] = trim(substr($buffer, 70, 4));
                $BUF_record["code_geographique"] = substr($buffer, 74, 5);
                $BUF_record["poids_entree"] = trim(substr($buffer, 79, 4));
                $BUF_record["age_gestationnel"] = trim(substr($buffer, 83, 2));
                $BUF_record["delai_dernieres_regles"] = trim(substr($buffer, 85, 3));
                $BUF_record["nombre_seances"] = trim(substr($buffer, 88, 2));
                $BUF_record["igs2"] = "000";
                $BUF_record["ghs_genrsa"] = trim(substr($buffer, 90, 4));
                $BUF_record["nb_exh"] = trim(substr($buffer, 94, 4));
                $BUF_record["type_exb"] = trim(substr($buffer, 98, 1));
                $BUF_record["nb_exb"] = trim(substr($buffer, 99, 3)); 
                $BUF_record["forfait_dialyse"] = "";

                // Nouveauté non exploitée : Top Admission Maison de Naissance 0:NON / 1:OUI
                $BUF_record["top_adm_maison_naissance"] = trim(substr($buffer, 102, 1));
                // Nouveauté non exploitée : Top Radiation partielle Avastin 0:NON / 1:OUI
                $BUF_record["top_radiation_part_avastin"] = trim(substr($buffer, 103, 1));
                // Nouveauté non exploitée : Top Radiation partielle Alimta 0:NON / 1:OUI
                $BUF_record["top_radiation_partielle_alimta"] = trim(substr($buffer, 104, 1));

                $BUF_record["top_uhcd"] = trim(substr($buffer, 105, 1));
                // top_ghs_minore : 0 = non | 1 = oui
                $BUF_record["top_ghs_minore"] = trim(substr($buffer, 106, 1));
                $BUF_record["confirmation_codage"] = trim(substr($buffer, 107, 1));
                // Nouveauté non exploitée : Nombre d'autorisations d'unités médicales à portée globale valides (Nb_AutPGV)
                $BUF_record["nb_aut_pgv"] = trim(substr($buffer, 108, 1));
                // -------------------------------------------------------------------------------------
                $BUF_record["nb_sup_dialyse_1"] = trim(substr($buffer, 109, 3));
                $BUF_record["nb_sup_dialyse_2"] = trim(substr($buffer, 112, 3));
                $BUF_record["nb_sup_dialyse_3"] = trim(substr($buffer, 115, 3));
                $BUF_record["nb_sup_dialyse_4"] = trim(substr($buffer, 118, 3));
                $BUF_record["nb_sup_apherese"] = trim(substr($buffer, 121, 3));
                // Nouveauté : Nombre de suppléments radiothérapie pédiatrique -------------------------
                $BUF_record["nb_sup_rap"] = trim(substr($buffer, 124, 3));
                // -------------------------------------------------------------------------------------
                // Nouveauté : Nombre de suppléments antepartum ----------------------------------------
                $BUF_record["nb_sup_ant"] = trim(substr($buffer, 127, 3));
                // -------------------------------------------------------------------------------------
                $BUF_record["nb_rdth"] = trim(substr($buffer, 130, 1));
                // top_valve_aortique : 1 si date sortie >=15/08/2012 + type autorisation UM 60 + acte pose, blanc sinon
                $BUF_record["top_valve_aortique"] = trim(substr($buffer, 131, 1));
                // type_generation_automatique: 0 = pas de génération automatique | 1 = FFM, ATU, SE | 2 = médecin salariés | 3 = dialyse
                $BUF_record["type_generation_automatique"] = trim(substr($buffer, 132, 1));
                $BUF_record["ghs_hors_innovation"] = trim(substr($buffer, 90, 4));
                $BUF_record["nb_seances_avant_sros"] = "00";
                $BUF_record["nb_sup_hyperbare"] = trim(substr($buffer, 145, 3));
                $BUF_record["type_prestation_prelevement_organe"] = trim(substr($buffer, 148, 1));
                $BUF_record["nb_sup_sra"] = "000";
                $BUF_record["nb_sup_rea"] = trim(substr($buffer, 149, 3));
                $BUF_record["nb_sup_si"] = trim(substr($buffer, 152, 3));
                $BUF_record["nb_sup_stf"] = trim(substr($buffer, 155, 3));
                $BUF_record["nb_sup_ssc"] = "000";
                $BUF_record["nb_sup_src"] = trim(substr($buffer, 158, 3));
                $BUF_record["nb_sup_nn1"] = trim(substr($buffer, 161, 3));
                $BUF_record["nb_sup_nn2"] = trim(substr($buffer, 164, 3));
                $BUF_record["nb_sup_nn3"] = trim(substr($buffer, 167, 3));
                $BUF_record["nb_sup_rep"] = trim(substr($buffer, 170, 3));
                $BUF_record["passage_lit_sp"] = trim(substr($buffer, 173, 1));
                $BUF_record["type_machine_rdth"] = trim(substr($buffer, 174, 1));
                $BUF_record["type_dosimetrie"] = trim(substr($buffer, 175, 1));
                $BUF_record["numero_innovation"] = trim(substr($buffer, 176, 15));
                $BUF_record["nombre_ivg_anterieures"] = "";
                $BUF_record["annee_ivg_precedente"] = "";
                $BUF_record["nombre_naissances_vivantes_anterieures"] = "";
                $BUF_record["nb_sup_sdc"] = trim(substr($buffer, 191, 1));
                $BUF_record["nb_faisceaux"] = "";
                $BUF_record["no_rum_dp"] = trim(substr($buffer, 200, 2));
                $BUF_record["diagnostic_principal"] = trim(substr($buffer, 202, 6));
                $BUF_record["diagnostic_relie"] = trim(substr($buffer, 208, 6));
                $BUF_record["nb_das"] = trim(substr($buffer, 214, 4));
                
                $BUF_aut_pgv_length = 2;
                
                $BUF_start = 238;
                $BUF_record["ok"] = TRUE;
                break;
			case "226" :
				// 226 - Applicable à compter de M03 2020
                $BUF_record["BUF_offsets"] = $rsa_offsets_226;
                $BUF_record["no_rsa"] = trim(substr($buffer, 12, 10));
                $BUF_record["version_format"] = trim(substr($buffer, 22, 3));
                $BUF_record["numero_tarif"] = trim(substr($buffer, 25, 3));
                $BUF_record["version_groupage"] = trim(substr($buffer, 28, 2));
                $BUF_record["ghm"] = trim(substr($buffer, 30, 6));
                $BUF_record["code_retour"] = trim(substr($buffer, 36, 3));
                $BUF_record["version_groupage_genrsa"] = trim(substr($buffer, 39, 2));
                $BUF_record["ghm_genrsa"] = trim(substr($buffer, 41, 6));
                $BUF_record["code_retour_genrsa"] = trim(substr($buffer, 47, 3));
                $BUF_record["nombre_rum"] = trim(substr($buffer, 50, 2));
                $BUF_record["age_annees"] = trim(substr($buffer, 52, 3));
                $BUF_record["age_jours"] = trim(substr($buffer, 55, 3));
                $BUF_record["sexe"] = trim(substr($buffer, 58, 1));
                $BUF_record["mode_entree"] = trim(substr($buffer, 59, 1));
                $BUF_record["provenance"] = trim(substr($buffer, 60, 1));
                $BUF_record["mois_sortie"]= trim(substr($buffer, 61, 6));
                $BUF_record["mode_sortie"] = trim(substr($buffer, 67, 1));
                $BUF_record["destination"] = trim(substr($buffer, 68, 1));
                $BUF_record["type_sejour"] = trim(substr($buffer, 69, 1));
                $BUF_record["duree_sejour"] = trim(substr($buffer, 70, 4));
                $BUF_record["code_geographique"] = substr($buffer, 74, 5);
                $BUF_record["poids_entree"] = trim(substr($buffer, 79, 4));
                $BUF_record["age_gestationnel"] = trim(substr($buffer, 83, 2));
                $BUF_record["delai_dernieres_regles"] = trim(substr($buffer, 85, 3));
                $BUF_record["nombre_seances"] = trim(substr($buffer, 93, 2));
                $BUF_record["igs2"] = "000";
                $BUF_record["ghs_genrsa"] = trim(substr($buffer, 95, 4));
                $BUF_record["nb_exh"] = trim(substr($buffer, 99, 4));
                $BUF_record["type_exb"] = trim(substr($buffer, 103, 1));
                $BUF_record["nb_exb"] = trim(substr($buffer, 104, 3)); 
                $BUF_record["forfait_dialyse"] = "";

                // Nouveauté non exploitée : Top Admission Maison de Naissance 0:NON / 1:OUI
                $BUF_record["top_adm_maison_naissance"] = trim(substr($buffer, 107, 1));
                // Nouveauté non exploitée : Top Radiation partielle Avastin 0:NON / 1:OUI
                $BUF_record["top_radiation_part_avastin"] = trim(substr($buffer, 108, 1));
                // Nouveauté non exploitée : Top Radiation partielle Alimta 0:NON / 1:OUI
                $BUF_record["top_radiation_partielle_alimta"] = trim(substr($buffer, 109, 1));

                $BUF_record["top_uhcd"] = trim(substr($buffer, 110, 1));
                // top_ghs_minore : 0 = non | 1 = oui
                $BUF_record["top_ghs_minore"] = trim(substr($buffer, 111, 1));
                $BUF_record["confirmation_codage"] = trim(substr($buffer, 112, 1));
                // Nouveauté non exploitée : Nombre d'autorisations d'unités médicales à portée globale valides (Nb_AutPGV)
                $BUF_record["nb_aut_pgv"] = trim(substr($buffer, 113, 1));
                // -------------------------------------------------------------------------------------
                $BUF_record["nb_sup_dialyse_1"] = trim(substr($buffer, 114, 3));
                $BUF_record["nb_sup_dialyse_2"] = trim(substr($buffer, 117, 3));
                $BUF_record["nb_sup_dialyse_3"] = trim(substr($buffer, 120, 3));
                $BUF_record["nb_sup_dialyse_4"] = trim(substr($buffer, 123, 3));
                $BUF_record["nb_sup_apherese"] = trim(substr($buffer, 126, 3));
                // Nouveauté : Nombre de suppléments radiothérapie pédiatrique -------------------------
                $BUF_record["nb_sup_rap"] = trim(substr($buffer, 129, 3));
                // -------------------------------------------------------------------------------------
                // Nouveauté : Nombre de suppléments antepartum ----------------------------------------
                $BUF_record["nb_sup_ant"] = trim(substr($buffer, 132, 3));
                // -------------------------------------------------------------------------------------
                $BUF_record["nb_rdth"] = trim(substr($buffer, 135, 1));
                // top_valve_aortique : 1 si date sortie >=15/08/2012 + type autorisation UM 60 + acte pose, blanc sinon
                $BUF_record["top_valve_aortique"] = trim(substr($buffer, 136, 1));
                // type_generation_automatique: 0 = pas de génération automatique | 1 = FFM, ATU, SE | 2 = médecin salariés | 3 = dialyse
                $BUF_record["type_generation_automatique"] = trim(substr($buffer, 137, 1));
                $BUF_record["ghs_hors_innovation"] = trim(substr($buffer, 95, 4));
                $BUF_record["nb_seances_avant_sros"] = "00";
                $BUF_record["nb_sup_hyperbare"] = trim(substr($buffer, 150, 3));
                $BUF_record["type_prestation_prelevement_organe"] = trim(substr($buffer, 153, 1));
                $BUF_record["nb_sup_sra"] = "000";
                $BUF_record["nb_sup_rea"] = trim(substr($buffer, 154, 3));
                $BUF_record["nb_sup_si"] = trim(substr($buffer, 157, 3));
                $BUF_record["nb_sup_stf"] = trim(substr($buffer, 160, 3));
                $BUF_record["nb_sup_ssc"] = "000";
                $BUF_record["nb_sup_src"] = trim(substr($buffer, 163, 3));
                $BUF_record["nb_sup_nn1"] = trim(substr($buffer, 166, 3));
                $BUF_record["nb_sup_nn2"] = trim(substr($buffer, 169, 3));
                $BUF_record["nb_sup_nn3"] = trim(substr($buffer, 172, 3));
                $BUF_record["nb_sup_rep"] = trim(substr($buffer, 175, 3));
                $BUF_record["passage_lit_sp"] = trim(substr($buffer, 178, 1));
                $BUF_record["type_machine_rdth"] = trim(substr($buffer, 179, 1));
                $BUF_record["type_dosimetrie"] = trim(substr($buffer, 180, 1));
                $BUF_record["numero_innovation"] = trim(substr($buffer, 182, 15));
                $BUF_record["nombre_ivg_anterieures"] = "";
                $BUF_record["annee_ivg_precedente"] = "";
                $BUF_record["nombre_naissances_vivantes_anterieures"] = "";
                $BUF_record["nb_sup_sdc"] = trim(substr($buffer, 196, 1));
                $BUF_record["nb_faisceaux"] = "";
                $BUF_record["no_rum_dp"] = trim(substr($buffer, 209, 2));
                $BUF_record["diagnostic_principal"] = trim(substr($buffer, 211, 6));
                $BUF_record["diagnostic_relie"] = trim(substr($buffer, 217, 6));
                $BUF_record["nb_das"] = trim(substr($buffer, 223, 4));
                
                $BUF_aut_pgv_length = 2;
                
                $BUF_start = 247;
                $BUF_record["ok"] = TRUE;
                break;
			case "227" :
				$BUF_record["BUF_offsets"] = $rsa_offsets_227;
                $BUF_record["no_rsa"] = trim(substr($buffer, 12, 10));
                $BUF_record["version_format"] = trim(substr($buffer, 22, 3));
                $BUF_record["numero_tarif"] = trim(substr($buffer, 25, 3));
                $BUF_record["version_groupage"] = trim(substr($buffer, 28, 2));
                $BUF_record["ghm"] = trim(substr($buffer, 30, 6));
                $BUF_record["code_retour"] = trim(substr($buffer, 36, 3));
                $BUF_record["version_groupage_genrsa"] = trim(substr($buffer, 39, 2));
                $BUF_record["ghm_genrsa"] = trim(substr($buffer, 41, 6));
                $BUF_record["code_retour_genrsa"] = trim(substr($buffer, 47, 3));
                $BUF_record["nombre_rum"] = trim(substr($buffer, 50, 2));
                $BUF_record["age_annees"] = trim(substr($buffer, 52, 3));
                $BUF_record["age_jours"] = trim(substr($buffer, 55, 3));
                $BUF_record["sexe"] = trim(substr($buffer, 58, 1));
                $BUF_record["mode_entree"] = trim(substr($buffer, 59, 1));
                $BUF_record["provenance"] = trim(substr($buffer, 60, 1));
                $BUF_record["mois_sortie"]= trim(substr($buffer, 61, 6));
                $BUF_record["mode_sortie"] = trim(substr($buffer, 67, 1));
                $BUF_record["destination"] = trim(substr($buffer, 68, 1));
                $BUF_record["type_sejour"] = trim(substr($buffer, 69, 1));
                $BUF_record["duree_sejour"] = trim(substr($buffer, 70, 4));
                $BUF_record["code_geographique"] = substr($buffer, 74, 5);
                $BUF_record["poids_entree"] = trim(substr($buffer, 79, 4));
                $BUF_record["age_gestationnel"] = trim(substr($buffer, 83, 2));
                $BUF_record["delai_dernieres_regles"] = trim(substr($buffer, 85, 3));
                $BUF_record["nombre_seances"] = trim(substr($buffer, 93, 2));
                $BUF_record["igs2"] = "000";
                $BUF_record["ghs_genrsa"] = trim(substr($buffer, 95, 4));
                $BUF_record["nb_exh"] = trim(substr($buffer, 99, 4));
                $BUF_record["type_exb"] = trim(substr($buffer, 103, 1));
                $BUF_record["nb_exb"] = trim(substr($buffer, 104, 3)); 
                $BUF_record["forfait_dialyse"] = "";

                // Nouveauté non exploitée : Top Admission Maison de Naissance 0:NON / 1:OUI
                $BUF_record["top_adm_maison_naissance"] = trim(substr($buffer, 107, 1));
                // Nouveauté non exploitée : Top Radiation partielle Avastin 0:NON / 1:OUI
                $BUF_record["top_radiation_part_avastin"] = trim(substr($buffer, 108, 1));
                // Nouveauté non exploitée : Top Radiation partielle Alimta 0:NON / 1:OUI
                $BUF_record["top_radiation_partielle_alimta"] = trim(substr($buffer, 109, 1));

                $BUF_record["top_uhcd"] = trim(substr($buffer, 110, 1));
                // top_ghs_minore : 0 = non | 1 = oui
                $BUF_record["top_ghs_minore"] = trim(substr($buffer, 111, 1));
                $BUF_record["confirmation_codage"] = trim(substr($buffer, 112, 1));
                // Nouveauté non exploitée : Nombre d'autorisations d'unités médicales à portée globale valides (Nb_AutPGV)
                $BUF_record["nb_aut_pgv"] = trim(substr($buffer, 113, 1));
                // -------------------------------------------------------------------------------------
                $BUF_record["nb_sup_dialyse_1"] = trim(substr($buffer, 114, 3));
                $BUF_record["nb_sup_dialyse_2"] = trim(substr($buffer, 117, 3));
                $BUF_record["nb_sup_dialyse_3"] = trim(substr($buffer, 120, 3));
                $BUF_record["nb_sup_dialyse_4"] = trim(substr($buffer, 123, 3));
                $BUF_record["nb_sup_apherese"] = trim(substr($buffer, 126, 3));
                // Nouveauté : Nombre de suppléments radiothérapie pédiatrique -------------------------
                $BUF_record["nb_sup_rap"] = trim(substr($buffer, 129, 3));
                // -------------------------------------------------------------------------------------
                // Nouveauté : Nombre de suppléments antepartum ----------------------------------------
                $BUF_record["nb_sup_ant"] = trim(substr($buffer, 132, 3));
                // -------------------------------------------------------------------------------------
                $BUF_record["nb_rdth"] = trim(substr($buffer, 135, 1));
                // top_valve_aortique : 1 si date sortie >=15/08/2012 + type autorisation UM 60 + acte pose, blanc sinon
                $BUF_record["top_valve_aortique"] = trim(substr($buffer, 136, 1));
                // type_generation_automatique: 0 = pas de génération automatique | 1 = FFM, ATU, SE | 2 = médecin salariés | 3 = dialyse
                $BUF_record["type_generation_automatique"] = trim(substr($buffer, 137, 1));
                $BUF_record["ghs_hors_innovation"] = trim(substr($buffer, 95, 4));
                $BUF_record["nb_seances_avant_sros"] = "00";
                $BUF_record["nb_sup_hyperbare"] = trim(substr($buffer, 150, 3));
                $BUF_record["type_prestation_prelevement_organe"] = trim(substr($buffer, 153, 1));
                $BUF_record["nb_sup_sra"] = "000";
                $BUF_record["nb_sup_rea"] = trim(substr($buffer, 154, 3));
                $BUF_record["nb_sup_si"] = trim(substr($buffer, 157, 3));
                $BUF_record["nb_sup_stf"] = trim(substr($buffer, 160, 3));
                $BUF_record["nb_sup_ssc"] = "000";
                $BUF_record["nb_sup_src"] = trim(substr($buffer, 163, 3));
                $BUF_record["nb_sup_nn1"] = trim(substr($buffer, 166, 3));
                $BUF_record["nb_sup_nn2"] = trim(substr($buffer, 169, 3));
                $BUF_record["nb_sup_nn3"] = trim(substr($buffer, 172, 3));
                $BUF_record["nb_sup_rep"] = trim(substr($buffer, 175, 3));
                $BUF_record["passage_lit_sp"] = trim(substr($buffer, 178, 1));
                $BUF_record["type_machine_rdth"] = trim(substr($buffer, 179, 1));
                $BUF_record["type_dosimetrie"] = trim(substr($buffer, 180, 1));
                $BUF_record["numero_innovation"] = trim(substr($buffer, 182, 15));
                $BUF_record["nombre_ivg_anterieures"] = "";
                $BUF_record["annee_ivg_precedente"] = "";
                $BUF_record["nombre_naissances_vivantes_anterieures"] = "";
                $BUF_record["nb_sup_sdc"] = trim(substr($buffer, 196, 1));
                $BUF_record["nb_faisceaux"] = "";
                $BUF_record["no_rum_dp"] = trim(substr($buffer, 209, 2));
                $BUF_record["diagnostic_principal"] = trim(substr($buffer, 211, 6));
                $BUF_record["diagnostic_relie"] = trim(substr($buffer, 217, 6));
                $BUF_record["nb_das"] = trim(substr($buffer, 223, 4));
                
                $BUF_aut_pgv_length = 2;
                
                $BUF_start = 247;
                $BUF_record["ok"] = TRUE;
                break;
             default :
                // 229 - Applicable à compter de M03 2025
                $BUF_record["BUF_offsets"] = $rsa_offsets_228;
                $BUF_record["no_rsa"] = trim(substr($buffer, 12, 10));
                $BUF_record["version_format"] = trim(substr($buffer, 22, 3));
                $BUF_record["numero_tarif"] = trim(substr($buffer, 25, 3));
                $BUF_record["version_groupage"] = trim(substr($buffer, 28, 2));
                $BUF_record["ghm"] = trim(substr($buffer, 30, 6));
                $BUF_record["code_retour"] = trim(substr($buffer, 36, 3));
                $BUF_record["version_groupage_genrsa"] = trim(substr($buffer, 39, 2));
                $BUF_record["ghm_genrsa"] = trim(substr($buffer, 41, 6));
                $BUF_record["code_retour_genrsa"] = trim(substr($buffer, 47, 3));
                $BUF_record["nombre_rum"] = trim(substr($buffer, 50, 2));
                $BUF_record["age_annees"] = trim(substr($buffer, 52, 3));
                $BUF_record["age_jours"] = trim(substr($buffer, 55, 3));
                $BUF_record["sexe"] = trim(substr($buffer, 58, 1));
                $BUF_record["mode_entree"] = trim(substr($buffer, 59, 1));
                $BUF_record["provenance"] = trim(substr($buffer, 60, 1));
                $BUF_record["mois_sortie"]= trim(substr($buffer, 61, 6));
                $BUF_record["mode_sortie"] = trim(substr($buffer, 67, 1));
                $BUF_record["destination"] = trim(substr($buffer, 68, 1));
                $BUF_record["type_sejour"] = trim(substr($buffer, 69, 1));
                $BUF_record["duree_sejour"] = trim(substr($buffer, 70, 4));
                $BUF_record["code_geographique"] = substr($buffer, 74, 5);
                $BUF_record["poids_entree"] = trim(substr($buffer, 79, 4));
                $BUF_record["age_gestationnel"] = trim(substr($buffer, 83, 2));
                $BUF_record["delai_dernieres_regles"] = trim(substr($buffer, 85, 3));
                $BUF_record["nombre_seances"] = trim(substr($buffer, 93, 2));
                $BUF_record["igs2"] = "000";
                $BUF_record["ghs_genrsa"] = trim(substr($buffer, 95, 4));
                $BUF_record["nb_exh"] = trim(substr($buffer, 99, 4));
                $BUF_record["type_exb"] = trim(substr($buffer, 103, 1));
                $BUF_record["nb_exb"] = trim(substr($buffer, 104, 3));
                $BUF_record["forfait_dialyse"] = "";

                // Nouveauté non exploitée : Top Admission Maison de Naissance 0:NON / 1:OUI
                $BUF_record["top_adm_maison_naissance"] = trim(substr($buffer, 107, 1));
                // Nouveauté non exploitée : Top Radiation partielle Avastin 0:NON / 1:OUI
                $BUF_record["top_radiation_part_avastin"] = trim(substr($buffer, 108, 1));
                // Nouveauté non exploitée : Top Radiation partielle Alimta 0:NON / 1:OUI
                $BUF_record["top_radiation_partielle_alimta"] = trim(substr($buffer, 109, 1));

                $BUF_record["top_uhcd"] = trim(substr($buffer, 110, 1));
                // top_ghs_minore : 0 = non | 1 = oui
                $BUF_record["top_ghs_minore"] = trim(substr($buffer, 111, 1));
                $BUF_record["confirmation_codage"] = trim(substr($buffer, 112, 1));
                // Nouveauté non exploitée : Nombre d'autorisations d'unités médicales à portée globale valides (Nb_AutPGV)
                $BUF_record["nb_aut_pgv"] = trim(substr($buffer, 113, 1));
                // -------------------------------------------------------------------------------------
                $BUF_record["nb_sup_dialyse_1"] = trim(substr($buffer, 114, 3));
                $BUF_record["nb_sup_dialyse_2"] = trim(substr($buffer, 117, 3));
                $BUF_record["nb_sup_dialyse_3"] = trim(substr($buffer, 120, 3));
                $BUF_record["nb_sup_dialyse_4"] = trim(substr($buffer, 123, 3));
                $BUF_record["nb_sup_apherese"] = trim(substr($buffer, 126, 3));
                // Nouveauté : Nombre de suppléments radiothérapie pédiatrique -------------------------
                $BUF_record["nb_sup_rap"] = trim(substr($buffer, 129, 3));
                // -------------------------------------------------------------------------------------
                // Nouveauté : Nombre de suppléments antepartum ----------------------------------------
                $BUF_record["nb_sup_ant"] = trim(substr($buffer, 132, 3));
                // -------------------------------------------------------------------------------------
                $BUF_record["nb_rdth"] = trim(substr($buffer, 135, 1));
                // top_valve_aortique : 1 si date sortie >=15/08/2012 + type autorisation UM 60 + acte pose, blanc sinon
                $BUF_record["top_valve_aortique"] = trim(substr($buffer, 136, 1));
                // type_generation_automatique: 0 = pas de génération automatique | 1 = FFM, ATU, SE | 2 = médecin salariés | 3 = dialyse
                $BUF_record["type_generation_automatique"] = trim(substr($buffer, 137, 1));
                $BUF_record["ghs_hors_innovation"] = trim(substr($buffer, 95, 4));
                $BUF_record["nb_seances_avant_sros"] = "00";
                $BUF_record["nb_sup_hyperbare"] = trim(substr($buffer, 150, 3));
                $BUF_record["type_prestation_prelevement_organe"] = trim(substr($buffer, 153, 1));
                $BUF_record["nb_sup_sra"] = "000";
                $BUF_record["nb_sup_rea"] = trim(substr($buffer, 154, 3));
                $BUF_record["nb_sup_si"] = trim(substr($buffer, 157, 3));
                $BUF_record["nb_sup_stf"] = trim(substr($buffer, 160, 3));
                $BUF_record["nb_sup_ssc"] = "000";
                $BUF_record["nb_sup_usip"] = trim(substr($buffer, 163, 3));
                $BUF_record["nb_sup_src"] = trim(substr($buffer, 166, 3));
                $BUF_record["nb_sup_nn1"] = trim(substr($buffer, 169, 3));
                $BUF_record["nb_sup_nn2"] = trim(substr($buffer, 172, 3));
                $BUF_record["nb_sup_nn3"] = trim(substr($buffer, 175, 3));
                $BUF_record["nb_sup_rep"] = trim(substr($buffer, 178, 3));
                $BUF_record["passage_lit_sp"] = trim(substr($buffer, 181, 1));
                $BUF_record["type_machine_rdth"] = trim(substr($buffer, 182, 1));
                $BUF_record["type_dosimetrie"] = trim(substr($buffer, 183, 1));
                $BUF_record["numero_innovation"] = trim(substr($buffer, 184, 15));
                $BUF_record["nombre_ivg_anterieures"] = "";
                $BUF_record["annee_ivg_precedente"] = "";
                $BUF_record["nombre_naissances_vivantes_anterieures"] = "";
                $BUF_record["nb_sup_sdc"] = trim(substr($buffer, 199, 1));
                $BUF_record["nb_faisceaux"] = "";
                $BUF_record["no_rum_dp"] = trim(substr($buffer, 212, 2));
                $BUF_record["diagnostic_principal"] = trim(substr($buffer, 214, 6));
                $BUF_record["diagnostic_relie"] = trim(substr($buffer, 220, 6));
                $BUF_record["nb_das"] = trim(substr($buffer, 226, 4));

                $BUF_aut_pgv_length = 2;

                //DRUIDE 2023
                $BUF_start = 265;

                $BUF_record["ok"] = true;
                break;

        }
    }
    
    // On passe les types d'autorisation à portée globale valide (à partir du format 219).
    $BUF_start += $BUF_record["nb_aut_pgv"] * $BUF_aut_pgv_length;
    
    $nb_rdth = get_num($BUF_record["nb_rdth"]);
    if ($nb_rdth > 0) {

        for ($i = 1; $i <=  $nb_rdth; $i++) {
            $BUF_record["supprdth"][$i]["ghs"] = trim(substr($buffer, $BUF_start, 4));
            $BUF_record["supprdth"][$i]["ghs_offset"] = $BUF_start;
            $BUF_record["supprdth"][$i]["ghs_len"] = 4;
            $BUF_record["supprdth"][$i]["nb_supplements"] = trim(substr($buffer, $BUF_start + 4, 3));
            $BUF_record["supprdth"][$i]["nb_supplements_offset"] = $BUF_start + 4;
            $BUF_record["supprdth"][$i]["nb_supplements_len"] = 3;
            $BUF_start += 7;
        }
    }
    return $BUF_record;
}

function read_ctl_line($buffer) {

    $BUF_record = array();

    $buffer = Encoding::removeBOM($buffer);
    
    $buffer = str_ireplace(";", "\t", $buffer);
    $array = split("\t", $buffer);

    
    $BUF_record["erreur_genrsa"] = trim(str_replace("\"", "", $array[0]));
    $BUF_record["erreur_genrsa_offset"] = 0;
    $BUF_record["erreur_genrsa_len"] = strlen($array[0]);
    $BUF_record["no_rss"] = trim(str_replace("\"", "", $array[1]));
    $BUF_record["no_rss_offset"] = $BUF_record["erreur_genrsa"] + $BUF_record["erreur_genrsa_len"] + 1;
    $BUF_record["no_rss_len"] = strlen($array[1]);
    $BUF_record["no_sejour_administratif"] = trim(str_replace("\"", "", $array[2]));
    $BUF_record["no_sejour_administratif_offset"] = $BUF_record["no_rss_offset"] + $BUF_record["no_rss_len"] + 1;
    $BUF_record["no_sejour_administratif_len"] = strlen($array[2]);
    
    $BUF_record["ok"] = TRUE;
    

    return $BUF_record;
        

}

function init_offsets() {

    init_ano_offests();
    global $rss_offsets_122;
	global $rss_offsets_121;
    global $rss_offsets_120;
	global $rss_offsets_119;
    global $rss_offsets_117;
    global $rss_offsets_114;
    global $rss_offsets_113;
    global $rss_offsets_111;
    global $rss_offsets_110;
    global $rss_offsets_109;

    global $rsf_offsets_2006_A;
    global $rsf_offsets_2006_B;
    global $rsf_offsets_2006_P;
    global $rsf_offsets_2006_M;
    global $rsf_offsets_2008_A;
    global $rsf_offsets_2008_B;
    global $rsf_offsets_2008_P;
    global $rsf_offsets_2008_M;
    global $rsf_offsets_2008B_M;
    global $rsf_offsets_2015_A;
    
    global $rsf_ace_offsets_2016_A;
    global $rsf_ace_offsets_2015_A;
    global $rsf_ace_offsets_2009_A;
    
    global $rsf_ace_offsets_2008_A;

    global $rsf_ace_offsets_2016_B; 
    global $rsf_ace_offsets_2008_B;
    global $rsf_ace_offsets_2008_C;
    global $rsf_ace_offsets_2008_M;
    
    global $rsf_ace_offsets_2007_A;
    global $rsf_ace_offsets_2007_C;
    global $rsf_ace_offsets_2007_M;
    
    global $fcp_dmi_offsets_2007;
    global $fcp_dmi_offsets_2008;
    global $fcp_ucd_offsets_2007;
    global $fcp_ucd_offsets_2008;

    
    global $rsa_offsets_215;
    global $rsa_offsets_222;
    global $rsa_offsets_227;
    global $rsa_offsets_228;
    global $rsa_offsets_229;
    global $tsp_offsets_2019;
    
    $tsp_offsets_2019 = array();
    $tsp_offsets_2019["finess_offset"] = 0;
    $tsp_offsets_2019["finess_len"] = 9;
    $tsp_offsets_2019["type_fichier_offset"] = 9;
    $tsp_offsets_2019["type_fichier_len"] = 3;
    $tsp_offsets_2019["annee_offset"] = 12;
    $tsp_offsets_2019["annee_len"] = 4;
    $tsp_offsets_2019["periode_offset"] = 16;
    $tsp_offsets_2019["periode_len"] = 2;
    $tsp_offsets_2019["code_offset"] = 18;
    $tsp_offsets_2019["code_len"] = 3;
    $tsp_offsets_2019["nb_sejours_offset"] = 21;
    $tsp_offsets_2019["nb_sejours_len"] = 10;
    
    
    $rss_offsets_119 = array();
	$rss_offsets_120 = array();
	$rss_offsets_121 = array();
	$rss_offsets_122 = array();
    $rss_offsets_117 = array();
    $rss_offsets_114 = array();
    $rss_offsets_113 = array();
    $rss_offsets_111 = array();
    $rss_offsets_110 = array();
    $rss_offsets_109 = array();
        
    
    
    $rss_offsets_117["version_groupage_offset"] = 0;
    $rss_offsets_117["version_groupage_len"] = 2;
    $rss_offsets_117["ghm_offset"] = 2;
    $rss_offsets_117["ghm_len"] = 6;
    $rss_offsets_117["version_format_offset"] = 9;
    $rss_offsets_117["version_format_len"] = 3;
    $rss_offsets_117["groupage_retour_offset"] = 12;
    $rss_offsets_117["groupage_retour_len"] = 3;
    $rss_offsets_117["finess_offset"] = 15;
    $rss_offsets_117["finess_len"] = 9;
    $rss_offsets_117["version_format_rum_offset"] = 24;
    $rss_offsets_117["version_format_rum_len"] = 3;

    $rss_offsets_117["no_rss_offset"] = 27;
    $rss_offsets_117["no_rss_len"] = 20;
    $rss_offsets_117["no_sejour_administratif_offset"] = 47;
    $rss_offsets_117["no_sejour_administratif_len"] = 20;
    $rss_offsets_117["no_rum_offset"] = 67;
    $rss_offsets_117["no_rum_len"] = 10;
    $rss_offsets_117["date_naissance_offset"] = 77;
    $rss_offsets_117["date_naissance_len"] = 8;
    $rss_offsets_117["sexe_offset"] = 85;
    $rss_offsets_117["sexe_len"] = 1;
    $rss_offsets_117["unite_medicale_offset"] = 86;
    $rss_offsets_117["unite_medicale_len"] = 4;
    $rss_offsets_117["type_autorisation_um_offset"] = 0;
    $rss_offsets_117["type_autorisation_um_len"] = 0;
    $rss_offsets_117["type_autorisation_lit_offset"] = 90;
    $rss_offsets_117["type_autorisation_lit_len"] = 2;
    $rss_offsets_117["date_entree_offset"] = 92;
    $rss_offsets_117["date_entree_len"] = 8;
    $rss_offsets_117["mode_entree_offset"] = 100;
    $rss_offsets_117["mode_entree_len"] = 1;
    $rss_offsets_117["provenance_offset"] = 101;
    $rss_offsets_117["provenance_len"] = 1;
    $rss_offsets_117["date_sortie_offset"] = 102;
    $rss_offsets_117["date_sortie_len"] = 8;
    $rss_offsets_117["mode_sortie_offset"] = 110;
    $rss_offsets_117["mode_sortie_len"] = 1;
    $rss_offsets_117["destination_offset"] = 111;
    $rss_offsets_117["destination_len"] = 1;
    $rss_offsets_117["code_postal_offset"] = 112;
    $rss_offsets_117["code_postal_len"] = 5;
    $rss_offsets_117["poids_bebe_offset"] = 117;
    $rss_offsets_117["poids_bebe_len"] = 4;
    $rss_offsets_117["age_gestationnel_offset"] = 121;
    $rss_offsets_117["age_gestationnel_len"] = 2;
    $rss_offsets_117["date_dernieres_regles_offset"] = 123;
    $rss_offsets_117["date_dernieres_regles_len"] = 8;
    $rss_offsets_117["nombre_seances_offset"] = 131;
    $rss_offsets_117["nombre_seances_len"] = 2;
    $rss_offsets_117["nombre_diagnostics_offset"] = 133;
    $rss_offsets_117["nombre_diagnostics_len"] = 2;
    $rss_offsets_117["nombre_donnees_documentaires_offset"] = 135;
    $rss_offsets_117["nombre_donnees_documentaires_len"] = 2;
    $rss_offsets_117["nombre_actes_offset"] = 137;
    $rss_offsets_117["nombre_actes_len"] = 3;
    $rss_offsets_117["diagnostic_principal_offset"] = 140;
    $rss_offsets_117["diagnostic_principal_len"] = 8;
    $rss_offsets_117["diagnostic_relie_offset"] = 148;
    $rss_offsets_117["diagnostic_relie_len"] = 8;
    $rss_offsets_117["igs2_offset"] = 156;
    $rss_offsets_117["igs2_len"] = 3;
    $rss_offsets_117["confirmation_codage_offset"] = 159;
    $rss_offsets_117["confirmation_codage_len"] = 1;
    $rss_offsets_117["type_machine_rdth_offset"] = 160;
    $rss_offsets_117["type_machine_rdth_len"] = 1;
    $rss_offsets_117["type_dosimetrie_offset"] = 161;
    $rss_offsets_117["type_dosimetrie_len"] = 1;
    $rss_offsets_117["numero_innovation_offset"] = 162;
    $rss_offsets_117["numero_innovation_len"] = 15;
    $rss_offsets_117["nombre_ivg_anterieures_offset"] = 177;
    $rss_offsets_117["nombre_ivg_anterieures_len"] = 2;
    $rss_offsets_117["annee_ivg_precedente_offset"] = 179;
    $rss_offsets_117["annee_ivg_precedente_len"] = 4;
    $rss_offsets_117["nombre_naissances_vivantes_anterieures_offset"] = 187;
    $rss_offsets_117["nombre_naissances_vivantes_anterieures_len"] = 2;
        
    $rss_offsets_119 = array_slice($rss_offsets_117,0,count($rss_offsets_117)); // hack de recopie de tableaux
    $rss_offsets_119["nombre_ivg_anterieures_offset"] = 0;
    $rss_offsets_119["nombre_ivg_anterieures_len"] = 0;
    $rss_offsets_119["annee_ivg_precedente_offset"] = 0;
    $rss_offsets_119["annee_ivg_precedente_len"] = 0;
    $rss_offsets_119["nombre_naissances_vivantes_anterieures_offset"] = 0;
    $rss_offsets_119["nombre_naissances_vivantes_anterieures_len"] = 0;
    $rss_offsets_119["conversion_hp_hc_offset"] = 177;
    $rss_offsets_119["conversion_hp_hc_len"] = 1;
    $rss_offsets_119["raac_offset"] = 178;
    $rss_offsets_119["raac_len"] = 1;
	
	$rss_offsets_119 = array_slice($rss_offsets_119,0,count($rss_offsets_119)); // hack de recopie de tableaux
	
	$rss_offsets_120 = array_slice($rss_offsets_120,0,count($rss_offsets_120)); // hack de recopie de tableaux
	
	$rss_offsets_121 = array_slice($rss_offsets_121,0,count($rss_offsets_121)); // hack de recopie de tableaux

	$rss_offsets_122 = array_slice($rss_offsets_122,0,count($rss_offsets_122)); // hack de recopie de tableaux
    $rss_offsets_122["passage_urgences_offset"] = 184;
    $rss_offsets_122["passage_urgences_len"] = 1;
    
    $rss_offsets_114["version_groupage_offset"] = 0;
    $rss_offsets_114["version_groupage_len"] = 2;
    $rss_offsets_114["ghm_offset"] = 2;
    $rss_offsets_114["ghm_len"] = 6;
    $rss_offsets_114["version_format_offset"] = 9;
    $rss_offsets_114["version_format_len"] = 3;
    $rss_offsets_114["groupage_retour_offset"] = 12;
    $rss_offsets_114["groupage_retour_len"] = 3;
    $rss_offsets_114["finess_offset"] = 15;
    $rss_offsets_114["finess_len"] = 9;
    $rss_offsets_114["version_format_rum_offset"] = 15;
    $rss_offsets_114["version_format_rum_len"] = 9;

    $rss_offsets_114["no_rss_offset"] = 27;
    $rss_offsets_114["no_rss_len"] = 20;
    $rss_offsets_114["no_sejour_administratif_offset"] = 47;
    $rss_offsets_114["no_sejour_administratif_len"] = 20;
    $rss_offsets_114["no_rum_offset"] = 67;
    $rss_offsets_114["no_rum_len"] = 10;
    $rss_offsets_114["date_naissance_offset"] = 77;
    $rss_offsets_114["date_naissance_len"] = 8;
    $rss_offsets_114["sexe_offset"] = 85;
    $rss_offsets_114["sexe_len"] = 1;
    $rss_offsets_114["unite_medicale_offset"] = 86;
    $rss_offsets_114["unite_medicale_len"] = 4;
    $rss_offsets_114["type_autorisation_um_offset"] = 0;
    $rss_offsets_114["type_autorisation_um_len"] = 0;
    $rss_offsets_114["type_autorisation_lit_offset"] = 90;
    $rss_offsets_114["type_autorisation_lit_len"] = 2;
    $rss_offsets_114["date_entree_offset"] = 92;
    $rss_offsets_114["date_entree_len"] = 8;
    $rss_offsets_114["mode_entree_offset"] = 100;
    $rss_offsets_114["mode_entree_len"] = 1;
    $rss_offsets_114["provenance_offset"] = 101;
    $rss_offsets_114["provenance_len"] = 1;
    $rss_offsets_114["date_sortie_offset"] = 102;
    $rss_offsets_114["date_sortie_len"] = 8;
    $rss_offsets_114["mode_sortie_offset"] = 110;
    $rss_offsets_114["mode_sortie_len"] = 1;
    $rss_offsets_114["destination_offset"] = 111;
    $rss_offsets_114["destination_len"] = 1;
    $rss_offsets_114["code_postal_offset"] = 112;
    $rss_offsets_114["code_postal_len"] = 5;
    $rss_offsets_114["poids_bebe_offset"] = 117;
    $rss_offsets_114["poids_bebe_len"] = 4;
    $rss_offsets_114["age_gestationnel_offset"] = 121;
    $rss_offsets_114["age_gestationnel_len"] = 2;
    $rss_offsets_114["nombre_seances_offset"] = 123;
    $rss_offsets_114["nombre_seances_len"] = 2;
    $rss_offsets_114["nombre_diagnostics_offset"] = 125;
    $rss_offsets_114["nombre_diagnostics_len"] = 2;
    $rss_offsets_114["nombre_donnees_documentaires_offset"] = 127;
    $rss_offsets_114["nombre_donnees_documentaires_len"] = 2;
    $rss_offsets_114["nombre_actes_offset"] = 129;
    $rss_offsets_114["nombre_actes_len"] = 3;
    $rss_offsets_114["diagnostic_principal_offset"] = 132;
    $rss_offsets_114["diagnostic_principal_len"] = 8;
    $rss_offsets_114["diagnostic_relie_offset"] = 140;
    $rss_offsets_114["diagnostic_relie_len"] = 8;
    $rss_offsets_114["igs2_offset"] = 148;
    $rss_offsets_114["igs2_len"] = 3;
    
    
    $rss_offsets_113["version_groupage_offset"] = 0;
    $rss_offsets_113["version_groupage_len"] = 2;
    $rss_offsets_113["ghm_offset"] = 2;
    $rss_offsets_113["ghm_len"] = 6;
    $rss_offsets_113["version_format_offset"] = 9;
    $rss_offsets_113["version_format_len"] = 3;
    $rss_offsets_113["groupage_retour_offset"] = 12;
    $rss_offsets_113["groupage_retour_len"] = 3;
    $rss_offsets_113["finess_offset"] = 15;
    $rss_offsets_113["finess_len"] = 9;
    $rss_offsets_113["version_format_rum_offset"] = 15;
    $rss_offsets_113["version_format_rum_len"] = 9;

    $rss_offsets_113["no_rss_offset"] = 27;
    $rss_offsets_113["no_rss_len"] = 20;
    $rss_offsets_113["no_sejour_administratif_offset"] = 47;
    $rss_offsets_113["no_sejour_administratif_len"] = 20;
    $rss_offsets_113["no_rum_offset"] = 67;
    $rss_offsets_113["no_rum_len"] = 10;
    $rss_offsets_113["date_naissance_offset"] = 77;
    $rss_offsets_113["date_naissance_len"] = 8;
    $rss_offsets_113["sexe_offset"] = 85;
    $rss_offsets_113["sexe_len"] = 1;
    $rss_offsets_113["unite_medicale_offset"] = 86;
    $rss_offsets_113["unite_medicale_len"] = 4;
    $rss_offsets_113["type_autorisation_um_offset"] = 0;
    $rss_offsets_113["type_autorisation_um_len"] = 0;
    $rss_offsets_113["type_autorisation_lit_offset"] = 90;
    $rss_offsets_113["type_autorisation_lit_len"] = 2;
    $rss_offsets_113["date_entree_offset"] = 92;
    $rss_offsets_113["date_entree_len"] = 8;
    $rss_offsets_113["mode_entree_offset"] = 100;
    $rss_offsets_113["mode_entree_len"] = 1;
    $rss_offsets_113["provenance_offset"] = 101;
    $rss_offsets_113["provenance_len"] = 1;
    $rss_offsets_113["date_sortie_offset"] = 102;
    $rss_offsets_113["date_sortie_len"] = 8;
    $rss_offsets_113["mode_sortie_offset"] = 110;
    $rss_offsets_113["mode_sortie_len"] = 1;
    $rss_offsets_113["destination_offset"] = 111;
    $rss_offsets_113["destination_len"] = 1;
    $rss_offsets_113["code_postal_offset"] = 112;
    $rss_offsets_113["code_postal_len"] = 5;
    $rss_offsets_113["poids_bebe_offset"] = 117;
    $rss_offsets_113["poids_bebe_len"] = 4;
    $rss_offsets_113["age_gestationnel_offset"] = 121;
    $rss_offsets_113["age_gestationnel_len"] = 2;
    $rss_offsets_113["nombre_seances_offset"] = 123;
    $rss_offsets_113["nombre_seances_len"] = 2;
    $rss_offsets_113["nombre_diagnostics_offset"] = 125;
    $rss_offsets_113["nombre_diagnostics_len"] = 2;
    $rss_offsets_113["nombre_donnees_documentaires_offset"] = 127;
    $rss_offsets_113["nombre_donnees_documentaires_len"] = 2;
    $rss_offsets_113["nombre_actes_offset"] = 129;
    $rss_offsets_113["nombre_actes_len"] = 2;
    $rss_offsets_113["diagnostic_principal_offset"] = 131;
    $rss_offsets_113["diagnostic_principal_len"] = 8;
    $rss_offsets_113["diagnostic_relie_offset"] = 139;
    $rss_offsets_113["diagnostic_relie_len"] = 8;
    $rss_offsets_113["igs2_offset"] = 147;
    $rss_offsets_113["igs2_len"] = 3;

    $rss_offsets_111["version_groupage_offset"] = 0;
    $rss_offsets_111["version_groupage_len"] = 2;
    $rss_offsets_111["ghm_offset"] = 2;
    $rss_offsets_111["ghm_len"] = 6;
    $rss_offsets_111["version_format_offset"] = 9;
    $rss_offsets_111["version_format_len"] = 3;
    $rss_offsets_111["groupage_retour_offset"] = 12;
    $rss_offsets_111["groupage_retour_len"] = 3;
    $rss_offsets_111["finess_offset"] = 15;
    $rss_offsets_111["finess_len"] = 9;
    $rss_offsets_111["version_format_rum_offset"] = 15;
    $rss_offsets_111["version_format_rum_len"] = 9; 

    $rss_offsets_111["no_rss_offset"] = 27;
    $rss_offsets_111["no_rss_len"] = 7;
    $rss_offsets_111["no_sejour_administratif_offset"] = 34;
    $rss_offsets_111["no_sejour_administratif_len"] = 20;
    $rss_offsets_111["no_rum_offset"] = 0;
    $rss_offsets_111["no_rum_len"] = 0;
    $rss_offsets_111["date_naissance_offset"] = 54;
    $rss_offsets_111["date_naissance_len"] = 8;
    $rss_offsets_111["sexe_offset"] = 62;
    $rss_offsets_111["sexe_len"] = 1;
    $rss_offsets_111["unite_medicale_offset"] = 63;
    $rss_offsets_111["unite_medicale_len"] = 4;
    $rss_offsets_111["type_autorisation_um_offset"] = 67;
    $rss_offsets_111["type_autorisation_um_len"] = 2;
    $rss_offsets_111["type_autorisation_lit_offset"] = 69;
    $rss_offsets_111["type_autorisation_lit_len"] = 2;
    $rss_offsets_111["date_entree_offset"] = 72;
    $rss_offsets_111["date_entree_len"] = 8;
    $rss_offsets_111["mode_entree_offset"] = 80;
    $rss_offsets_111["mode_entree_len"] = 1;
    $rss_offsets_111["provenance_offset"] = 81;
    $rss_offsets_111["provenance_len"] = 1;
    $rss_offsets_111["date_sortie_offset"] = 182;
    $rss_offsets_111["date_sortie_len"] = 8;
    $rss_offsets_111["mode_sortie_offset"] = 90;
    $rss_offsets_111["mode_sortie_len"] = 1;
    $rss_offsets_111["destination_offset"] = 91;
    $rss_offsets_111["destination_len"] = 1;
    $rss_offsets_111["code_postal_offset"] = 92;
    $rss_offsets_111["code_postal_len"] = 5;
    $rss_offsets_111["poids_bebe_offset"] = 97;
    $rss_offsets_111["poids_bebe_len"] = 4;
    $rss_offsets_111["age_gestationnel_offset"] = 0;
    $rss_offsets_111["age_gestationnel_len"] = 0;
    $rss_offsets_111["nombre_seances_offset"] = 101;
    $rss_offsets_111["nombre_seances_len"] = 2;
    $rss_offsets_111["nombre_diagnostics_offset"] = 103;
    $rss_offsets_111["nombre_diagnostics_len"] = 2;
    $rss_offsets_111["nombre_donnees_documentaires_offset"] = 105;
    $rss_offsets_111["nombre_donnees_documentaires_len"] = 2;
    $rss_offsets_111["nombre_actes_offset"] = 107;
    $rss_offsets_111["nombre_actes_len"] = 2;
    $rss_offsets_111["diagnostic_principal_offset"] = 109;
    $rss_offsets_111["diagnostic_principal_len"] = 8;
    $rss_offsets_111["diagnostic_relie_offset"] = 117;
    $rss_offsets_111["diagnostic_relie_len"] = 8;
    $rss_offsets_111["igs2_offset"] = 125;
    $rss_offsets_111["igs2_len"] = 3;
            
            
    $rss_offsets_110["version_groupage_offset"] = 0;
    $rss_offsets_110["version_groupage_len"] = 2;
    $rss_offsets_110["ghm_offset"] = 2;
    $rss_offsets_110["ghm_len"] = 6;
    $rss_offsets_110["version_format_offset"] = 9;
    $rss_offsets_110["version_format_len"] = 3;
    $rss_offsets_110["groupage_retour_offset"] = 12;
    $rss_offsets_110["groupage_retour_len"] = 3;
    $rss_offsets_110["finess_offset"] = 15;
    $rss_offsets_110["finess_len"] = 9;
    $rss_offsets_110["version_format_rum_offset"] = 15;
    $rss_offsets_110["version_format_rum_len"] = 9;         
    
    $rss_offsets_110["no_rss_offset"] = 27;
    $rss_offsets_110["no_rss_len"] = 7;
    $rss_offsets_110["no_sejour_administratif_offset"] = 0;
    $rss_offsets_110["no_sejour_administratif_len"] = 0;
    $rss_offsets_110["no_rum_offset"] = 0;
    $rss_offsets_110["no_rum_len"] = 0;
    $rss_offsets_110["date_naissance_offset"] = 34;
    $rss_offsets_110["date_naissance_len"] = 8;
    $rss_offsets_110["sexe_offset"] = 42;
    $rss_offsets_110["sexe_len"] = 1;
    $rss_offsets_110["unite_medicale_offset"] = 43;
    $rss_offsets_110["unite_medicale_len"] = 4;
    $rss_offsets_110["type_autorisation_um_offset"] = 0;
    $rss_offsets_110["type_autorisation_um_len"] = 0;
    $rss_offsets_110["type_autorisation_lit_offset"] = 0;
    $rss_offsets_110["type_autorisation_lit_len"] = 0;
    $rss_offsets_110["date_entree_offset"] = 47;
    $rss_offsets_110["date_entree_len"] = 8;
    $rss_offsets_110["mode_entree_offset"] = 55;
    $rss_offsets_110["mode_entree_len"] = 1;
    $rss_offsets_110["provenance_offset"] = 56;
    $rss_offsets_110["provenance_len"] = 1;
    $rss_offsets_110["date_sortie_offset"] = 57;
    $rss_offsets_110["date_sortie_len"] = 8;
    $rss_offsets_110["mode_sortie_offset"] = 65;
    $rss_offsets_110["mode_sortie_len"] = 1;
    $rss_offsets_110["destination_offset"] = 66;
    $rss_offsets_110["destination_len"] = 1;
    $rss_offsets_110["code_postal_offset"] = 67;
    $rss_offsets_110["code_postal_len"] = 5;
    $rss_offsets_110["poids_bebe_offset"] = 72;
    $rss_offsets_110["poids_bebe_len"] = 4;
    $rss_offsets_110["age_gestationnel_offset"] = 0;
    $rss_offsets_110["age_gestationnel_len"] = 0;
    $rss_offsets_110["nombre_seances_offset"] = 76;
    $rss_offsets_110["nombre_seances_len"] = 2;
    $rss_offsets_110["nombre_diagnostics_offset"] = 78;
    $rss_offsets_110["nombre_diagnostics_len"] = 2;
    $rss_offsets_110["nombre_donnees_documentaires_offset"] = 80;
    $rss_offsets_110["nombre_donnees_documentaires_len"] = 2;
    $rss_offsets_110["nombre_actes_offset"] = 82;
    $rss_offsets_110["nombre_actes_len"] = 2;
    $rss_offsets_110["diagnostic_principal_offset"] = 84;
    $rss_offsets_110["diagnostic_principal_len"] = 8;
    $rss_offsets_110["diagnostic_relie_offset"] = 92;
    $rss_offsets_110["diagnostic_relie_len"] = 8;
    $rss_offsets_110["igs2_offset"] = 100;
    $rss_offsets_110["igs2_len"] = 3;
    
    $rss_offsets_110["version_groupage_offset"] = 0;
    $rss_offsets_110["version_groupage_len"] = 2;
    $rss_offsets_110["ghm_offset"] = 2;
    $rss_offsets_110["ghm_len"] = 6;
    $rss_offsets_110["version_format_offset"] = 9;
    $rss_offsets_110["version_format_len"] = 3;
    $rss_offsets_110["groupage_retour_offset"] = 12;
    $rss_offsets_110["groupage_retour_len"] = 3;
    $rss_offsets_110["finess_offset"] = 15;
    $rss_offsets_110["finess_len"] = 9;
    $rss_offsets_110["version_format_rum_offset"] = 15;
    $rss_offsets_110["version_format_rum_len"] = 9;         
    
    $rss_offsets_109["no_rss_offset"] = 27;
    $rss_offsets_109["no_rss_len"] = 7;
    $rss_offsets_109["no_sejour_administratif_offset"] = 0;
    $rss_offsets_109["no_sejour_administratif_len"] = 0;
    $rss_offsets_109["no_rum_offset"] = 0;
    $rss_offsets_109["no_rum_len"] = 0;
    $rss_offsets_109["date_naissance_offset"] = 34;
    $rss_offsets_109["date_naissance_len"] = 8;
    $rss_offsets_109["sexe_offset"] = 42;
    $rss_offsets_109["sexe_len"] = 1;
    $rss_offsets_109["unite_medicale_offset"] = 43;
    $rss_offsets_109["unite_medicale_len"] = 4;
    $rss_offsets_109["type_autorisation_um_offset"] = 0;
    $rss_offsets_109["type_autorisation_um_len"] = 0;
    $rss_offsets_109["type_autorisation_lit_offset"] = 0;
    $rss_offsets_109["type_autorisation_lit_len"] = 0;
    $rss_offsets_109["date_entree_offset"] = 47;
    $rss_offsets_109["date_entree_len"] = 8;
    $rss_offsets_109["mode_entree_offset"] = 55;
    $rss_offsets_109["mode_entree_len"] = 1;
    $rss_offsets_109["provenance_offset"] = 56;
    $rss_offsets_109["provenance_len"] = 1;
    $rss_offsets_109["date_sortie_offset"] = 57;
    $rss_offsets_109["date_sortie_len"] = 8;
    $rss_offsets_109["mode_sortie_offset"] = 65;
    $rss_offsets_109["mode_sortie_len"] = 1;
    $rss_offsets_109["destination_offset"] = 66;
    $rss_offsets_109["destination_len"] = 1;
    $rss_offsets_109["code_postal_offset"] = 67;
    $rss_offsets_109["code_postal_len"] = 5;
    $rss_offsets_109["poids_bebe_offset"] = 72;
    $rss_offsets_109["poids_bebe_len"] = 4;
    $rss_offsets_109["age_gestationnel_offset"] = 0;
    $rss_offsets_109["age_gestationnel_len"] = 0;
    $rss_offsets_109["nombre_seances_offset"] = 76;
    $rss_offsets_109["nombre_seances_len"] = 2;
    $rss_offsets_109["nombre_diagnostics_offset"] = 78;
    $rss_offsets_109["nombre_diagnostics_len"] = 2;
    $rss_offsets_109["nombre_donnees_documentaires_offset"] = 80;
    $rss_offsets_109["nombre_donnees_documentaires_len"] = 2;
    $rss_offsets_109["nombre_actes_offset"] = 82;
    $rss_offsets_109["nombre_actes_len"] = 2;
    $rss_offsets_109["diagnostic_principal_offset"] = 84;
    $rss_offsets_109["diagnostic_principal_len"] = 8;
    $rss_offsets_109["diagnostic_relie_offset"] = 92;
    $rss_offsets_109["diagnostic_relie_len"] = 8;
    $rss_offsets_109["igs2_offset"] = 100;
    $rss_offsets_109["igs2_len"] = 3;
    
    
    $rsf_offsets_2006_A = array();
    $rsf_offsets_2006_B = array();
    $rsf_offsets_2006_P = array();
    $rsf_offsets_2006_M = array();
    $rsf_offsets_2008_A = array();
    $rsf_offsets_2008_B = array();
    $rsf_offsets_2008_P = array();
    $rsf_offsets_2008_M = array();
    $rsf_offsets_2008B_M = array();
    $rsf_offsets_2015_A = array();
    
    $rsf_offsets_2015_A["finess_offset"] = 1;
    $rsf_offsets_2015_A["finess_len"] = 9;
    $rsf_offsets_2015_A["no_rss_offset"] = 10;
    $rsf_offsets_2015_A["no_rss_len"] = 20;
    $rsf_offsets_2015_A["sexe_offset"] = 30;
    $rsf_offsets_2015_A["sexe_len"] = 1;
    $rsf_offsets_2015_A["civilite_offset"] = 31;
    $rsf_offsets_2015_A["civilite_len"] = 1;
    $rsf_offsets_2015_A["immatriculation_assure_offset"] = 32;
    $rsf_offsets_2015_A["immatriculation_assure_len"] = 13;
    $rsf_offsets_2015_A["cle_immatriculation_assure_offset"] = 45;
    $rsf_offsets_2015_A["cle_immatriculation_assure_len"] = 2;
    $rsf_offsets_2015_A["rang_beneficiaire_offset"] = 47;
    $rsf_offsets_2015_A["rang_beneficiaire_len"] = 3;
    $rsf_offsets_2015_A["no_facture_offset"] = 50;
    $rsf_offsets_2015_A["no_facture_len"] = 9;
    $rsf_offsets_2015_A["nature_operation_offset"] = 59;
    $rsf_offsets_2015_A["nature_operation_len"] = 1;
    $rsf_offsets_2015_A["nature_assurance_offset"] = 60;
    $rsf_offsets_2015_A["nature_assurance_len"] = 2;
    $rsf_offsets_2015_A["type_contrat_oc_offset"] = 62;
    $rsf_offsets_2015_A["type_contrat_oc_len"] = 2;
    $rsf_offsets_2015_A["justificatif_exo_offset"] = 64;
    $rsf_offsets_2015_A["justificatif_exo_len"] = 1;
    $rsf_offsets_2015_A["code_pec_offset"] = 65;
    $rsf_offsets_2015_A["code_pec_len"] = 1;
    $rsf_offsets_2015_A["grand_regime_offset"] = 66;
    $rsf_offsets_2015_A["grand_regime_len"] = 2;
    $rsf_offsets_2015_A["date_naissance_offset"] = 68;
    $rsf_offsets_2015_A["date_naissance_len"] = 8;
    $rsf_offsets_2015_A["rang_naissance_offset"] = 76;
    $rsf_offsets_2015_A["rang_naissance_len"] = 1;
    $rsf_offsets_2015_A["date_entree_offset"] = 77;
    $rsf_offsets_2015_A["date_entree_len"] = 8;
    $rsf_offsets_2015_A["date_sortie_offset"] = 85;
    $rsf_offsets_2015_A["date_sortie_len"] = 8;
    $rsf_offsets_2015_A["base_remboursement_c_offset"] = 93;
    $rsf_offsets_2015_A["base_remboursement_c_len"] = 8;
    $rsf_offsets_2015_A["total_remboursable_amo_offset"] = 101;
    $rsf_offsets_2015_A["total_remboursable_amo_len"] = 8;
    $rsf_offsets_2015_A["total_honoraires_factures_offset"] = 109;
    $rsf_offsets_2015_A["total_honoraires_factures_len"] = 8;
    $rsf_offsets_2015_A["total_honoraires_remboursable_offset"] = 117;
    $rsf_offsets_2015_A["total_honoraires_remboursable_len"] = 8;
    $rsf_offsets_2015_A["total_assure_avant_oc_offset"] = 125;
    $rsf_offsets_2015_A["total_assure_avant_oc_len"] = 8;
    $rsf_offsets_2015_A["total_remboursable_oc_ph_offset"] = 133;
    $rsf_offsets_2015_A["total_remboursable_oc_ph_len"] = 8;
    $rsf_offsets_2015_A["total_remboursable_oc_honoraires_offset"] = 141;
    $rsf_offsets_2015_A["total_remboursable_oc_honoraires_len"] = 8;
    $rsf_offsets_2015_A["total_facture_phoffset"] = 149;
    $rsf_offsets_2015_A["total_facture_ph_len"] = 8;
    $rsf_offsets_2015_A["etat_liquidation_offset"] = 157;
    $rsf_offsets_2015_A["etat_liquidation_len"] = 1;
    $rsf_offsets_2015_A["pat_benef_cmu_offset"] = 158;
    $rsf_offsets_2015_A["pat_benef_cmu_len"] = 1;
    $rsf_offsets_2015_A["no_facture_sejour_mere_offset"] = 159;
    $rsf_offsets_2015_A["no_facture_sejour_mere_len"] = 9;
    $rsf_offsets_2015_A["no_organisme_complementaire_offset"] = 168;
    $rsf_offsets_2015_A["no_organisme_complementaire_len"] = 10;
    $rsf_offsets_2015_A["no_at_date_adc_offset"] = 178;
    $rsf_offsets_2015_A["no_at_date_adc_len"] = 9;
    
    $rsf_offsets_2008_A["finess_offset"] = 1;
    $rsf_offsets_2008_A["finess_len"] = 9;
    $rsf_offsets_2008_A["no_rss_offset"] = 10;
    $rsf_offsets_2008_A["no_rss_len"] = 20;
    $rsf_offsets_2008_A["sexe_offset"] = 30;
    $rsf_offsets_2008_A["sexe_len"] = 1;
    $rsf_offsets_2008_A["civilite_offset"] = 31;
    $rsf_offsets_2008_A["civilite_len"] = 1;
    $rsf_offsets_2008_A["immatriculation_assure_offset"] = 32;
    $rsf_offsets_2008_A["immatriculation_assure_len"] = 13;
    $rsf_offsets_2008_A["cle_immatriculation_assure_offset"] = 45;
    $rsf_offsets_2008_A["cle_immatriculation_assure_len"] = 2;
    $rsf_offsets_2008_A["rang_beneficiaire_offset"] = 47;
    $rsf_offsets_2008_A["rang_beneficiaire_len"] = 3;
    $rsf_offsets_2008_A["no_facture_offset"] = 50;
    $rsf_offsets_2008_A["no_facture_len"] = 9;
    $rsf_offsets_2008_A["nature_operation_offset"] = 59;
    $rsf_offsets_2008_A["nature_operation_len"] = 1;
    $rsf_offsets_2008_A["nature_assurance_offset"] = 60;
    $rsf_offsets_2008_A["nature_assurance_len"] = 1;
    $rsf_offsets_2008_A["type_contrat_oc_offset"] = 62;
    $rsf_offsets_2008_A["type_contrat_oc_len"] = 2;
    $rsf_offsets_2008_A["justificatif_exo_offset"] = 64;
    $rsf_offsets_2008_A["justificatif_exo_len"] = 1;
    $rsf_offsets_2008_A["code_pec_offset"] = 65;
    $rsf_offsets_2008_A["code_pec_len"] = 1;
    $rsf_offsets_2008_A["grand_regime_offset"] = 66;
    $rsf_offsets_2008_A["grand_regime_len"] = 2;
    $rsf_offsets_2008_A["date_naissance_offset"] = 68;
    $rsf_offsets_2008_A["date_naissance_len"] = 8;
    $rsf_offsets_2008_A["rang_naissance_offset"] = 76;
    $rsf_offsets_2008_A["rang_naissance_len"] = 1;
    $rsf_offsets_2008_A["date_entree_offset"] = 77;
    $rsf_offsets_2008_A["date_entree_len"] = 8;
    $rsf_offsets_2008_A["date_sortie_offset"] = 85;
    $rsf_offsets_2008_A["date_sortie_len"] = 8;
    $rsf_offsets_2008_A["base_remboursement_c_offset"] = 93;
    $rsf_offsets_2008_A["base_remboursement_c_len"] = 8;
    $rsf_offsets_2008_A["total_remboursable_amo_offset"] = 101;
    $rsf_offsets_2008_A["total_remboursable_amo_len"] = 8;
    $rsf_offsets_2008_A["total_honoraires_factures_offset"] = 109;
    $rsf_offsets_2008_A["total_honoraires_factures_len"] = 8;
    $rsf_offsets_2008_A["total_honoraires_remboursable_offset"] = 117;
    $rsf_offsets_2008_A["total_honoraires_remboursable_len"] = 8;
    $rsf_offsets_2008_A["total_assure_avant_oc_offset"] = 125;
    $rsf_offsets_2008_A["total_assure_avant_oc_len"] = 8;
    $rsf_offsets_2008_A["total_remboursable_oc_ph_offset"] = 133;
    $rsf_offsets_2008_A["total_remboursable_oc_ph_len"] = 8;
    $rsf_offsets_2008_A["total_remboursable_oc_honoraires_offset"] = 141;
    $rsf_offsets_2008_A["total_remboursable_oc_honoraires_len"] = 8;
    $rsf_offsets_2008_A["total_facture_phoffset"] = 149;
    $rsf_offsets_2008_A["total_facture_ph_len"] = 8;
    $rsf_offsets_2008_A["etat_liquidation_offset"] = 157;
    $rsf_offsets_2008_A["etat_liquidation_len"] = 1;
    $rsf_offsets_2008_A["pat_benef_cmu_offset"] = 158;
    $rsf_offsets_2008_A["pat_benef_cmu_len"] = 1;
    $rsf_offsets_2008_A["no_facture_sejour_mere_offset"] = 159;
    $rsf_offsets_2008_A["no_facture_sejour_mere_len"] = 9;
    
    $rsf_offsets_2006_A["finess_offset"] = 1;
    $rsf_offsets_2006_A["finess_len"] = 9;
    $rsf_offsets_2006_A["no_rss_offset"] = 10;
    $rsf_offsets_2006_A["no_rss_len"] = 7;
    $rsf_offsets_2006_A["sexe_offset"] = 17;
    $rsf_offsets_2006_A["sexe_len"] = 1;
    $rsf_offsets_2006_A["civilite_offset"] = 18;
    $rsf_offsets_2006_A["civilite_len"] = 1;
    $rsf_offsets_2006_A["immatriculation_assure_offset"] = 19;
    $rsf_offsets_2006_A["immatriculation_assure_len"] = 13;
    $rsf_offsets_2006_A["cle_immatriculation_assure_offset"] = 0;
    $rsf_offsets_2006_A["cle_immatriculation_assure_len"] = 0;
    $rsf_offsets_2006_A["rang_beneficiaire_offset"] = 32;
    $rsf_offsets_2006_A["rang_beneficiaire_len"] = 3;
    $rsf_offsets_2006_A["nature_operation_offset"] = 35;
    $rsf_offsets_2006_A["nature_operation_len"] = 1;
    $rsf_offsets_2006_A["nature_assurance_offset"] = 36;
    $rsf_offsets_2006_A["nature_assurance_len"] = 1;
    $rsf_offsets_2006_A["type_contrat_oc_offset"] = 0;
    $rsf_offsets_2006_A["type_contrat_oc_len"] = 0;
    $rsf_offsets_2006_A["justificatif_exo_offset"] = 38;
    $rsf_offsets_2006_A["justificatif_exo_len"] = 1;
    $rsf_offsets_2006_A["code_pec_offset"] = 39;
    $rsf_offsets_2006_A["code_pec_len"] = 1;
    $rsf_offsets_2006_A["no_facture_offset"] = 40;
    $rsf_offsets_2006_A["no_facture_len"] = 9;
    $rsf_offsets_2006_A["grand_regime_offset"] = 49;
    $rsf_offsets_2006_A["grand_regime_len"] = 2;
    $rsf_offsets_2006_A["date_naissance_offset"] = 51;
    $rsf_offsets_2006_A["date_naissance_len"] = 8;
    $rsf_offsets_2006_A["rang_naissance_offset"] = 59;
    $rsf_offsets_2006_A["rang_naissance_len"] = 1;
    $rsf_offsets_2006_A["date_entree_offset"] = 60;
    $rsf_offsets_2006_A["date_entree_len"] = 8;
    $rsf_offsets_2006_A["date_sortie_offset"] = 68;
    $rsf_offsets_2006_A["date_sortie_len"] = 8;
    $rsf_offsets_2006_A["base_remboursement_c_offset"] = 76;
    $rsf_offsets_2006_A["base_remboursement_c_len"] = 8;
    $rsf_offsets_2006_A["total_remboursable_amo_offset"] = 84;
    $rsf_offsets_2006_A["total_remboursable_amo_len"] = 8;
    $rsf_offsets_2006_A["total_honoraires_factures_offset"] = 92;
    $rsf_offsets_2006_A["total_honoraires_factures_len"] = 8;
    $rsf_offsets_2006_A["total_honoraires_remboursable_offset"] = 100;
    $rsf_offsets_2006_A["total_honoraires_remboursable_len"] = 8;
    $rsf_offsets_2006_A["total_assure_avant_oc_offset"] = 108;
    $rsf_offsets_2006_A["total_assure_avant_oc_len"] = 8;
    $rsf_offsets_2006_A["total_remboursable_oc_ph_offset"] = 116;
    $rsf_offsets_2006_A["total_remboursable_oc_ph_len"] = 8;
    $rsf_offsets_2006_A["total_remboursable_oc_honoraires_offset"] = 124;
    $rsf_offsets_2006_A["total_remboursable_oc_honoraires_len"] = 8;
    $rsf_offsets_2006_A["total_facture_ph_offset"] = 132;
    $rsf_offsets_2006_A["total_facture_ph_len"] = 8;
    $rsf_offsets_2006_A["etat_liquidation_offset"] = 0;
    $rsf_offsets_2006_A["etat_liquidation_len"] = 0;
    
    
    
    $rsf_offsets_2008_B["finess_offset"] = 1;
    $rsf_offsets_2008_B["finess_len"] = 9;
    $rsf_offsets_2008_B["no_rss_offset"] = 10;
    $rsf_offsets_2008_B["no_rss_len"] = 20;
    $rsf_offsets_2008_B["sexe_offset"] = 30;
    $rsf_offsets_2008_B["sexe_len"] = 1;
    $rsf_offsets_2008_B["immatriculation_assure_offset"] = 32;
    $rsf_offsets_2008_B["immatriculation_assure_len"] = 13;
    $rsf_offsets_2008_B["rang_beneficiaire_offset"] = 45;
    $rsf_offsets_2008_B["rang_beneficiaire_len"] = 3;
    $rsf_offsets_2008_B["no_facture_offset"] = 48;
    $rsf_offsets_2008_B["no_facture_len"] = 9;
    $rsf_offsets_2008_B["mode_traitement_offset"] = 57;
    $rsf_offsets_2008_B["mode_traitement_len"] = 2;
    $rsf_offsets_2008_B["discpline_prestation_offset"] = 59;
    $rsf_offsets_2008_B["discpline_prestation_len"] = 3;
    $rsf_offsets_2008_B["date_debut_offset"] = 62;
    $rsf_offsets_2008_B["date_debut_len"] = 8;
    $rsf_offsets_2008_B["date_fin_offset"] = 70;
    $rsf_offsets_2008_B["date_fin_len"] = 8;
    $rsf_offsets_2008_B["code_acte_offset"] = 78;
    $rsf_offsets_2008_B["code_acte_len"] = 5;
    $rsf_offsets_2008_B["nombre_offset"] = 83;
    $rsf_offsets_2008_B["nombre_len"] = 3;
    $rsf_offsets_2008_B["justificatif_exo_offset"] = 86;
    $rsf_offsets_2008_B["justificatif_exo_len"] = 1;
    $rsf_offsets_2008_B["coefficient_offset"] = 87;
    $rsf_offsets_2008_B["coefficient_len"] = 5;
    $rsf_offsets_2008_B["code_pec_fj_offset"] = 92;
    $rsf_offsets_2008_B["code_pec_fj_len"] = 1;
    $rsf_offsets_2008_B["coefficient_mco_offset"] = 93;
    $rsf_offsets_2008_B["coefficient_mco_len"] = 5;
    $rsf_offsets_2008_B["prix_unitaire_offset"] = 98;
    $rsf_offsets_2008_B["prix_unitaire_len"] = 7;
    $rsf_offsets_2008_B["base_remboursement_offset"] = 105;
    $rsf_offsets_2008_B["base_remboursement_len"] = 8;
    $rsf_offsets_2008_B["taux_offset"] = 113;
    $rsf_offsets_2008_B["taux_len"] = 3;
    $rsf_offsets_2008_B["montant_remboursable_offset"] = 116;
    $rsf_offsets_2008_B["montant_remboursable_len"] = 8;
    $rsf_offsets_2008_B["montant_total_depense_offset"] = 124;
    $rsf_offsets_2008_B["montant_total_depense_len"] = 8;
    $rsf_offsets_2008_B["montant_remboursable_oc_offset"] = 132;
    $rsf_offsets_2008_B["montant_remboursable_oc_len"] = 7;
    $rsf_offsets_2008_B["no_ghs_offset"] = 139;
    $rsf_offsets_2008_B["no_ghs_len"] = 4;
    $rsf_offsets_2008_B["montant_remboursé_noemie_offset"] = 143;
    $rsf_offsets_2008_B["montant_remboursé_noemie_len"] = 8;
    $rsf_offsets_2008_B["nature_noemie_offset"] = 151;
    $rsf_offsets_2008_B["nature_noemie_len"] = 3;
                
                
                
    $rsf_offsets_2006_B["finess_offset"] = 1;
    $rsf_offsets_2006_B["finess_len"] = 9;          
    $rsf_offsets_2006_B["no_rss_offset"] = 10;
    $rsf_offsets_2006_B["no_rss_len"] = 7;
    $rsf_offsets_2006_B["sexe"] = "";
    $rsf_offsets_2006_B["sexe_offset"] = 0;
    $rsf_offsets_2006_B["sexe_len"] = 0;
    $rsf_offsets_2006_B["immatriculation_assure_offset"] = 17;
    $rsf_offsets_2006_B["immatriculation_assure_len"] = 13;
    $rsf_offsets_2006_B["rang_beneficiaire_offset"] = 30;
    $rsf_offsets_2006_B["rang_beneficiaire_len"] = 3;
    $rsf_offsets_2006_B["no_facture"] = "";
    $rsf_offsets_2006_B["no_facture_offset"] = 0;
    $rsf_offsets_2006_B["no_facture_len"] = 0;
    $rsf_offsets_2006_B["mode_traitement_offset"] = 33;
    $rsf_offsets_2006_B["mode_traitement_len"] = 2;
    $rsf_offsets_2006_B["discpline_prestation_offset"] = 35;
    $rsf_offsets_2006_B["discpline_prestation_len"] = 3;
    $rsf_offsets_2006_B["date_debut_offset"] = 38;
    $rsf_offsets_2006_B["date_debut_len"] = 8;
    $rsf_offsets_2006_B["date_fin_offset"] = 46;
    $rsf_offsets_2006_B["date_fin_len"] = 8;
    $rsf_offsets_2006_B["code_acte_offset"] = 54;
    $rsf_offsets_2006_B["code_acte_len"] = 5;
    $rsf_offsets_2006_B["nombre_offset"] = 59;
    $rsf_offsets_2006_B["nombre_len"] = 3;
    $rsf_offsets_2006_B["justificatif_exo_offset"] = 62;
    $rsf_offsets_2006_B["justificatif_exo_len"] = 1;
    $rsf_offsets_2006_B["coefficient_offset"] = 63;
    $rsf_offsets_2006_B["coefficient_len"] = 5;
    $rsf_offsets_2006_B["code_pec_fj_offset"] = 68;
    $rsf_offsets_2006_B["code_pec_fj_len"] = 1;
    $rsf_offsets_2006_B["coefficient_mco_offset"] = 69;
    $rsf_offsets_2006_B["coefficient_mco_len"] = 5;
    $rsf_offsets_2006_B["prix_unitaire_offset"] = 74;
    $rsf_offsets_2006_B["prix_unitaire_len"] = 7;
    $rsf_offsets_2006_B["base_remboursement_offset"] = 81;
    $rsf_offsets_2006_B["base_remboursement_len"] = 8;
    $rsf_offsets_2006_B["taux_offset"] = 89;
    $rsf_offsets_2006_B["taux_len"] = 3;
    $rsf_offsets_2006_B["montant_remboursable_offset"] = 92;
    $rsf_offsets_2006_B["montant_remboursable_len"] = 8;
    $rsf_offsets_2006_B["montant_total_depense_offset"] = 100;
    $rsf_offsets_2006_B["montant_total_depense_len"] = 8;
    $rsf_offsets_2006_B["montant_remboursable_oc_offset"] = 108;
    $rsf_offsets_2006_B["montant_remboursable_oc_len"] = 7;
    $rsf_offsets_2006_B["no_ghs_offset"] = 115;
    $rsf_offsets_2006_B["no_ghs_len"] = 4;
    $rsf_offsets_2006_B["montant_remboursé_noemie_offset"] = 119;
    $rsf_offsets_2006_B["montant_remboursé_noemie_len"] = 8;
    $rsf_offsets_2006_B["nature_noemie_offset"] = 127;
    $rsf_offsets_2006_B["nature_noemie_len"] = 3;
                
                
    $rsf_offsets_2008_P["finess_offset"] = 1;
    $rsf_offsets_2008_P["finess_len"] = 9;          
    $rsf_offsets_2008_P["no_rss_offset"] = 10;
    $rsf_offsets_2008_P["no_rss_len"] = 20;
    $rsf_offsets_2008_P["immatriculation_assure_offset"] = 30;
    $rsf_offsets_2008_P["immatriculation_assure_len"] = 13;
    $rsf_offsets_2008_P["cle_immatriculation_assure_offset"] = 43;
    $rsf_offsets_2008_P["cle_immatriculation_assure_len"] = 2;
    $rsf_offsets_2008_P["rang_beneficiaire_offset"] = 45;
    $rsf_offsets_2008_P["rang_beneficiaire_len"] = 3;
    $rsf_offsets_2008_P["no_facture_offset"] = 48;
    $rsf_offsets_2008_P["no_facture_len"] = 9;
    $rsf_offsets_2008_P["date_debut_offset"] = 57;
    $rsf_offsets_2008_P["date_debut_len"] = 8;
    $rsf_offsets_2008_P["code_lpp_offset"] = 65;
    $rsf_offsets_2008_P["code_lpp_len"] = 13;
    $rsf_offsets_2008_P["nombre_offset"] = 78;
    $rsf_offsets_2008_P["nombre_len"] = 2;
    $rsf_offsets_2008_P["prix_unitaire_offset"] = 80;
    $rsf_offsets_2008_P["prix_unitaire_len"] = 7;
    $rsf_offsets_2008_P["montant_facture_offset"] = 87;
    $rsf_offsets_2008_P["montant_facture_len"] = 7;
    $rsf_offsets_2008_P["code_lpp_2_offset"] = 0;
    $rsf_offsets_2008_P["code_lpp_2_len"] = 0;
    $rsf_offsets_2008_P["nombre_2_offset"] = 0;
    $rsf_offsets_2008_P["nombre_2_len"] = 0;
    $rsf_offsets_2008_P["prix_unitaire_2_offset"] = 0;
    $rsf_offsets_2008_P["prix_unitaire_2_len"] = 0;
    $rsf_offsets_2008_P["montant_facture_2_offset"] = 0;
    $rsf_offsets_2008_P["montant_facture_2_len"] = 0;
    
    
    $rsf_offsets_2006_P["finess_offset"] = 1;
    $rsf_offsets_2006_P["finess_len"] = 9;
    $rsf_offsets_2006_P["no_rss_offset"] = 10;
    $rsf_offsets_2006_P["no_rss_len"] = 7;
    $rsf_offsets_2006_P["immatriculation_assure_offset"] = 17;
    $rsf_offsets_2006_P["immatriculation_assure_len"] = 13;
    $rsf_offsets_2006_P["cle_immatriculation_assure_offset"] = 0;
    $rsf_offsets_2006_P["cle_immatriculation_assure_len"] = 0;
    $rsf_offsets_2006_P["rang_beneficiaire_offset"] = 30;
    $rsf_offsets_2006_P["rang_beneficiaire_len"] = 3;
    $rsf_offsets_2006_P["no_facture_offset"] = 0;
    $rsf_offsets_2006_P["no_facture_len"] = 0;
    $rsf_offsets_2006_P["date_debut_offset"] = 33;
    $rsf_offsets_2006_P["date_debut_len"] = 8;
    $rsf_offsets_2006_P["code_lpp_offset"] = 41;
    $rsf_offsets_2006_P["code_lpp_len"] = 13;
    $rsf_offsets_2006_P["nombre_offset"] = 54;
    $rsf_offsets_2006_P["nombre_len"] = 2;
    $rsf_offsets_2006_P["prix_unitaire_offset"] = 56;
    $rsf_offsets_2006_P["prix_unitaire_len"] = 7;
    $rsf_offsets_2006_P["montant_facture_offset"] = 63;
    $rsf_offsets_2006_P["montant_facture_len"] = 7;
    $rsf_offsets_2006_P["code_lpp_2_offset"] = 70;
    $rsf_offsets_2006_P["code_lpp_2_len"] = 13;
    $rsf_offsets_2006_P["nombre_2_offset"] = 83;
    $rsf_offsets_2006_P["nombre_2_len"] = 2;
    $rsf_offsets_2006_P["prix_unitaire_2_offset"] = 85;
    $rsf_offsets_2006_P["prix_unitaire_2_len"] = 7;
    $rsf_offsets_2006_P["montant_facture_2_offset"] = 92;
    $rsf_offsets_2006_P["montant_facture_2_len"] = 7;
    
    
    $rsf_offsets_2008_H["finess_offset"] = 1;
    $rsf_offsets_2008_H["finess_len"] = 9;          
    $rsf_offsets_2008_H["no_rss_offset"] = 10;
    $rsf_offsets_2008_H["no_rss_len"] = 20;
    $rsf_offsets_2008_H["immatriculation_assure_offset"] = 30;
    $rsf_offsets_2008_H["immatriculation_assure_len"] = 13;
    $rsf_offsets_2008_H["cle_immatriculation_assure_offset"] = 43;
    $rsf_offsets_2008_H["cle_immatriculation_assure_len"] = 2;
    $rsf_offsets_2008_H["rang_beneficiaire_offset"] = 45;
    $rsf_offsets_2008_H["rang_beneficiaire_len"] = 3;
    $rsf_offsets_2008_H["no_facture_offset"] = 48;
    $rsf_offsets_2008_H["no_facture_len"] = 9;
    $rsf_offsets_2008_H["date_debut_offset"] = 57;
    $rsf_offsets_2008_H["date_debut_len"] = 8;
    $rsf_offsets_2008_H["code_ucd_offset"] = 65;
    $rsf_offsets_2008_H["code_ucd_len"] = 7;
    $rsf_offsets_2008_H["coefficient_factionnement_offset"] = 72;
    $rsf_offsets_2008_H["coefficient_factionnement_len"] = 5;
    $rsf_offsets_2008_H["prix_unitaire_achat_offset"] = 77;
    $rsf_offsets_2008_H["prix_unitaire_achat_len"] = 7;
    $rsf_offsets_2008_H["prix_unitaire_ecart_indemnisable_offset"] = 84;
    $rsf_offsets_2008_H["prix_unitaire_ecart_indemnisable_len"] = 7;
    $rsf_offsets_2008_H["montant_ecart_indemnisable_offset"] = 91;
    $rsf_offsets_2008_H["montant_ecart_indemnisable_len"] = 7;
    $rsf_offsets_2008_H["nombre_offset"] = 98;
    $rsf_offsets_2008_H["nombre_len"] = 3;
    $rsf_offsets_2008_H["montant_facture_offset"] = 101;
    $rsf_offsets_2008_H["montant_facture_len"] = 7;
    
    $rsf_offsets_2006_H["finess_offset"] = 1;
    $rsf_offsets_2006_H["finess_len"] = 9;          
    $rsf_offsets_2006_H["no_rss_offset"] = 10;
    $rsf_offsets_2006_H["no_rss_len"] = 7;
    $rsf_offsets_2006_H["immatriculation_assure_offset"] = 17;
    $rsf_offsets_2006_H["immatriculation_assure_len"] = 13;
    $rsf_offsets_2006_H["cle_immatriculation_assure_offset"] = 0;
    $rsf_offsets_2006_H["cle_immatriculation_assure_len"] = 0;
    $rsf_offsets_2006_H["rang_beneficiaire_offset"] = 30;
    $rsf_offsets_2006_H["rang_beneficiaire_len"] = 3;
    $rsf_offsets_2006_H["no_facture_offset"] = 0;
    $rsf_offsets_2006_H["no_facture_len"] = 0;
    $rsf_offsets_2006_H["date_debut_offset"] = 33;
    $rsf_offsets_2006_H["date_debut_len"] = 8;
    $rsf_offsets_2006_H["code_ucd_offset"] = 41;
    $rsf_offsets_2006_H["code_ucd_len"] = 7;
    $rsf_offsets_2006_H["coefficient_factionnement_offset"] = 0;
    $rsf_offsets_2006_H["coefficient_factionnement_len"] = 0;
    $rsf_offsets_2006_H["prix_unitaire_achat_offset"] = 49;
    $rsf_offsets_2006_H["prix_unitaire_achat_len"] = 7;
    $rsf_offsets_2006_H["prix_unitaire_ecart_indemnisable_offset"] = 0;
    $rsf_offsets_2006_H["prix_unitaire_ecart_indemnisable_len"] = 0;
    $rsf_offsets_2006_H["montant_ecart_indemnisable_offset"] = 56;
    $rsf_offsets_2006_H["montant_ecart_indemnisable_len"] = 7;
    $rsf_offsets_2006_H["nombre_offset"] = 71;
    $rsf_offsets_2006_H["nombre_len"] = 3;
    $rsf_offsets_2006_H["montant_facture_offset"] = 73;
    $rsf_offsets_2006_H["montant_facture_len"] = 7;
    
    
    $rsf_offsets_2008_M["finess_offset"] = 1;
    $rsf_offsets_2008_M["finess_len"] = 9;
    $rsf_offsets_2008_M["no_rss_offset"] = 10;
    $rsf_offsets_2008_M["no_rss_len"] = 20;
    $rsf_offsets_2008_M["immatriculation_assure_offset"] = 30;
    $rsf_offsets_2008_M["immatriculation_assure_len"] = 13;
    $rsf_offsets_2008_M["cle_immatriculation_assure_offset"] = 43;
    $rsf_offsets_2008_M["cle_immatriculation_assure_len"] = 2;
    $rsf_offsets_2008_M["rang_beneficiaire_offset"] = 45;
    $rsf_offsets_2008_M["rang_beneficiaire_len"] = 3;
    $rsf_offsets_2008_M["no_facture_offset"] = 48;
    $rsf_offsets_2008_M["no_facture_len"] = 9;
    $rsf_offsets_2008_M["mode_traitement_offset"] = 57;
    $rsf_offsets_2008_M["mode_traitement_len"] = 2;
    $rsf_offsets_2008_M["discpline_prestation_offset"] = 59;
    $rsf_offsets_2008_M["discpline_prestation_len"] = 3;
    $rsf_offsets_2008_M["date_acte_offset"] = 62;
    $rsf_offsets_2008_M["date_acte_len"] = 8;
    $rsf_offsets_2008_M["code_acte_offset"] = 70;
    $rsf_offsets_2008_M["code_acte_len"] = 7;
    $rsf_offsets_2008_M["extension_ccam_offset"] = 83;
    $rsf_offsets_2008_M["extension_ccam_len"] = 1;
    $rsf_offsets_2008_M["activite_ccam_offset"] = 84;
    $rsf_offsets_2008_M["activite_ccam_len"] = 1;
    $rsf_offsets_2008_M["phase_ccam_offset"] = 85;
    $rsf_offsets_2008_M["phase_ccam_len"] = 1;
    $rsf_offsets_2008_M["modificateur_ccam_1_offset"] = 86;
    $rsf_offsets_2008_M["modificateur_ccam_1_len"] = 1;
    $rsf_offsets_2008_M["modificateur_ccam_2_offset"] = 87;
    $rsf_offsets_2008_M["modificateur_ccam_2_len"] = 1;
    $rsf_offsets_2008_M["modificateur_ccam_3_offset"] = 88;
    $rsf_offsets_2008_M["modificateur_ccam_3_len"] = 1;
    $rsf_offsets_2008_M["modificateur_ccam_4_offset"] = 89;
    $rsf_offsets_2008_M["modificateur_ccam_4_len"] = 1;
    $rsf_offsets_2008_M["association_nonprevue_ccam_offset"] = 90;
    $rsf_offsets_2008_M["association_nonprevue_ccam_len"] = 1;
    $rsf_offsets_2008_M["remboursement_excp_ccam_offset"] = 91;
    $rsf_offsets_2008_M["remboursement_excp_ccam_len"] = 1;
                
    $rsf_offsets_2008B_M["finess_offset"] = 1;
    $rsf_offsets_2008B_M["finess_len"] = 9;         
    $rsf_offsets_2008B_M["no_rss_offset"] = 10;
    $rsf_offsets_2008B_M["no_rss_len"] = 20;
    $rsf_offsets_2008B_M["immatriculation_assure_offset"] = 30;
    $rsf_offsets_2008B_M["immatriculation_assure_len"] = 13;
    $rsf_offsets_2008B_M["cle_immatriculation_assure_offset"] = 43;
    $rsf_offsets_2008B_M["cle_immatriculation_assure_len"] = 2;
    $rsf_offsets_2008B_M["rang_beneficiaire_offset"] = 45;
    $rsf_offsets_2008B_M["rang_beneficiaire_len"] = 3;
    $rsf_offsets_2008B_M["no_facture_offset"] = 48;
    $rsf_offsets_2008B_M["no_facture_len"] = 9;
    $rsf_offsets_2008B_M["mode_traitement_offset"] = 57;
    $rsf_offsets_2008B_M["mode_traitement_len"] = 2;
    $rsf_offsets_2008B_M["discpline_prestation_offset"] = 59;
    $rsf_offsets_2008B_M["discpline_prestation_len"] = 3;
    $rsf_offsets_2008B_M["date_acte_offset"] = 62;
    $rsf_offsets_2008B_M["date_acte_len"] = 8;
    $rsf_offsets_2008B_M["code_acte_offset"] = 76;
    $rsf_offsets_2008B_M["code_acte_len"] = 7;
    $rsf_offsets_2008B_M["extension_ccam_offset"] = 83;
    $rsf_offsets_2008B_M["extension_ccam_len"] = 1;
    $rsf_offsets_2008B_M["activite_ccam_offset"] = 84;
    $rsf_offsets_2008B_M["activite_ccam_len"] = 1;
    $rsf_offsets_2008B_M["phase_ccam_offset"] = 85;
    $rsf_offsets_2008B_M["phase_ccam_len"] = 1;
    $rsf_offsets_2008B_M["modificateur_ccam_1_offset"] = 86;
    $rsf_offsets_2008B_M["modificateur_ccam_1_len"] = 1;
    $rsf_offsets_2008B_M["modificateur_ccam_2_offset"] = 87;
    $rsf_offsets_2008B_M["modificateur_ccam_2_len"] = 1;
    $rsf_offsets_2008B_M["modificateur_ccam_3_offset"] = 88;
    $rsf_offsets_2008B_M["modificateur_ccam_3_len"] = 1;
    $rsf_offsets_2008B_M["modificateur_ccam_4_offset"] = 89;
    $rsf_offsets_2008B_M["modificateur_ccam_4_len"] = 1;
    $rsf_offsets_2008B_M["association_nonprevue_ccam_offset"] = 90;
    $rsf_offsets_2008B_M["association_nonprevue_ccam_len"] = 1;
    $rsf_offsets_2008B_M["remboursement_excp_ccam_offset"] = 91;
    $rsf_offsets_2008B_M["remboursement_excp_ccam_len"] = 1;
                
                
    $rsf_offsets_2006_M["finess_offset"] = 1;
    $rsf_offsets_2006_M["finess_len"] = 9;          
    $rsf_offsets_2006_M["no_rss_offset"] = 10;
    $rsf_offsets_2006_M["no_rss_len"] = 7;
    $rsf_offsets_2006_M["immatriculation_assure_offset"] = 17;
    $rsf_offsets_2006_M["immatriculation_assure_len"] = 13;
    $rsf_offsets_2006_M["cle_immatriculation_assure_offset"] = 0;
    $rsf_offsets_2006_M["cle_immatriculation_assure_len"] = 0;
    $rsf_offsets_2006_M["rang_beneficiaire_offset"] = 30;
    $rsf_offsets_2006_M["rang_beneficiaire_len"] = 3;
    $rsf_offsets_2006_M["no_facture_offset"] = 0;
    $rsf_offsets_2006_M["no_facture_len"] = 0;
    $rsf_offsets_2006_M["mode_traitement_offset"] = 33;
    $rsf_offsets_2006_M["mode_traitement_len"] = 2;
    $rsf_offsets_2006_M["discpline_prestation_offset"] = 35;
    $rsf_offsets_2006_M["discpline_prestation_len"] = 3;
    $rsf_offsets_2006_M["date_acte_offset"] = 38;
    $rsf_offsets_2006_M["date_acte_len"] = 8;
    $rsf_offsets_2006_M["code_acte_offset"] = 46;
    $rsf_offsets_2006_M["code_acte_len"] = 7;
    $rsf_offsets_2006_M["extension_ccam_offset"] = 59;
    $rsf_offsets_2006_M["extension_ccam_len"] = 1;
    $rsf_offsets_2006_M["activite_ccam_offset"] = 60;
    $rsf_offsets_2006_M["activite_ccam_len"] = 1;
    $rsf_offsets_2006_M["phase_ccam_offset"] = 61;
    $rsf_offsets_2006_M["phase_ccam_len"] = 1;
    $rsf_offsets_2006_M["modificateur_ccam_1_offset"] = 62;
    $rsf_offsets_2006_M["modificateur_ccam_1_len"] = 1;
    $rsf_offsets_2006_M["modificateur_ccam_2_offset"] = 63;
    $rsf_offsets_2006_M["modificateur_ccam_2_len"] = 1;
    $rsf_offsets_2006_M["modificateur_ccam_3_offset"] = 64;
    $rsf_offsets_2006_M["modificateur_ccam_3_len"] = 1;
    $rsf_offsets_2006_M["modificateur_ccam_4_offset"] = 65;
    $rsf_offsets_2006_M["modificateur_ccam_4_len"] = 1;
    $rsf_offsets_2006_M["association_nonprevue_ccam_offset"] = 66;
    $rsf_offsets_2006_M["association_nonprevue_ccam_len"] = 1;
    $rsf_offsets_2006_M["remboursement_excp_ccam_offset"] = 67;
    $rsf_offsets_2006_M["remboursement_excp_ccam_len"] = 1;
    
    $rsf_ace_offsets_2016_A = array();
    $rsf_ace_offsets_2015_A = array();
    $rsf_ace_offsets_2009_A = array();
    
    $rsf_ace_offsets_2008_A = array();
    $rsf_ace_offsets_2008_B = array();
    $rsf_ace_offsets_2016_B = array();

    $rsf_ace_offsets_2008_M = array();
    
    $rsf_ace_offsets_2007_A = array();
    $rsf_ace_offsets_2007_M = array();
    
    $rsf_ace_offsets_2016_A["finess_offset"] = 1;
    $rsf_ace_offsets_2016_A["finess_len"] = 9;
    $rsf_ace_offsets_2016_A["finess_geographique_offset"] = 10;
    $rsf_ace_offsets_2016_A["finess_geographique_len"] = 9;
    $rsf_ace_offsets_2016_A["sexe_offset"] = 19;
    $rsf_ace_offsets_2016_A["sexe_len"] = 1;
    $rsf_ace_offsets_2016_A["civilite_offset"] = 20;
    $rsf_ace_offsets_2016_A["civilite_len"] = 1;
    $rsf_ace_offsets_2016_A["immatriculation_assure_offset"] = 21;
    $rsf_ace_offsets_2016_A["immatriculation_assure_len"] = 13;
    $rsf_ace_offsets_2016_A["cle_immatriculation_assure_offset"] = 34;
    $rsf_ace_offsets_2016_A["cle_immatriculation_assure_len"] = 2;
    $rsf_ace_offsets_2016_A["rang_beneficiaire_offset"] = 36;
    $rsf_ace_offsets_2016_A["rang_beneficiaire_len"] = 3;
    $rsf_ace_offsets_2016_A["no_facture_offset"] = 39;
    $rsf_ace_offsets_2016_A["no_facture_len"] = 9;
    $rsf_ace_offsets_2016_A["indicateur_parcours_soins_offset"] = 48;
    $rsf_ace_offsets_2016_A["indicateur_parcours_soins_len"] = 1;
    $rsf_ace_offsets_2016_A["nature_operation_offset"] = 49;
    $rsf_ace_offsets_2016_A["nature_operation_len"] = 1;
    $rsf_ace_offsets_2016_A["nature_assurance_offset"] = 50;
    $rsf_ace_offsets_2016_A["nature_assurance_len"] = 2;
    $rsf_ace_offsets_2016_A["justificatif_exo_offset"] = 52;
    $rsf_ace_offsets_2016_A["justificatif_exo_len"] = 1;
    $rsf_ace_offsets_2016_A["code_pec_offset"] = 53;
    $rsf_ace_offsets_2016_A["code_pec_len"] = 1;
    $rsf_ace_offsets_2016_A["motif_non_facturation_offset"] = 54;
    $rsf_ace_offsets_2016_A["motif_non_facturation_len"] = 1;
    $rsf_ace_offsets_2016_A["grand_regime_offset"] = 55;
    $rsf_ace_offsets_2016_A["grand_regime_len"] = 2;
    $rsf_ace_offsets_2016_A["date_naissance_offset"] = 57;
    $rsf_ace_offsets_2016_A["date_naissance_len"] = 8;
    $rsf_ace_offsets_2016_A["rang_naissance_offset"] = 65;
    $rsf_ace_offsets_2016_A["rang_naissance_len"] = 1;
    $rsf_ace_offsets_2016_A["date_entree_offset"] = 66;
    $rsf_ace_offsets_2016_A["date_entree_len"] = 8;
    $rsf_ace_offsets_2016_A["date_sortie_offset"] = 74;
    $rsf_ace_offsets_2016_A["date_sortie_len"] = 8;
    $rsf_ace_offsets_2016_A["code_postal_offset"] = 82;
    $rsf_ace_offsets_2016_A["code_postal_len"] = 5;
    $rsf_ace_offsets_2016_A["base_remboursement_c_offset"] = 87;
    $rsf_ace_offsets_2016_A["base_remboursement_c_len"] = 8;
    $rsf_ace_offsets_2016_A["total_remboursable_amo_offset"] = 95;
    $rsf_ace_offsets_2016_A["total_remboursable_amo_len"] = 8;
    $rsf_ace_offsets_2016_A["total_honoraires_factures_offset"] = 103;
    $rsf_ace_offsets_2016_A["total_honoraires_factures_len"] = 8;
    $rsf_ace_offsets_2016_A["total_honoraires_remboursable_offset"] = 111;
    $rsf_ace_offsets_2016_A["total_honoraires_remboursable_len"] = 8;
    $rsf_ace_offsets_2016_A["total_assure_avant_oc_offset"] = 119;
    $rsf_ace_offsets_2016_A["total_assure_avant_oc_len"] = 8;
    $rsf_ace_offsets_2016_A["total_remboursable_oc_ph_offset"] = 127;
    $rsf_ace_offsets_2016_A["total_remboursable_oc_ph_len"] = 8;
    $rsf_ace_offsets_2016_A["total_remboursable_oc_honoraires_offset"] = 135;
    $rsf_ace_offsets_2016_A["total_remboursable_oc_honoraires_len"] = 8;
    $rsf_ace_offsets_2016_A["total_facture_ph_offset"] = 143;
    $rsf_ace_offsets_2016_A["total_facture_ph_len"] = 8;
    $rsf_ace_offsets_2016_A["pat_benef_cmu_offset"] = 151;
    $rsf_ace_offsets_2016_A["pat_benef_cmu_len"] = 1;
    $rsf_ace_offsets_2016_A["valorise_fides_offset"] = 152;
    $rsf_ace_offsets_2016_A["valorise_fides_len"] = 1;
    $rsf_ace_offsets_2016_A["code_gestion_offset"] = 153;
    $rsf_ace_offsets_2016_A["code_gestion_len"] = 2;
    $rsf_ace_offsets_2016_A["no_organisme_complementaire_offset"] = 155;
    $rsf_ace_offsets_2016_A["no_organisme_complementaire_len"] = 10;
    $rsf_ace_offsets_2016_A["no_at_date_adc_offset"] = 165;
    $rsf_ace_offsets_2016_A["no_at_date_adc_len"] = 9;

    $rsf_ace_offsets_2015_A["finess_offset"] = 1;
    $rsf_ace_offsets_2015_A["finess_len"] = 9;
    $rsf_ace_offsets_2015_A["sexe_offset"] = 10;
    $rsf_ace_offsets_2015_A["sexe_len"] = 1;
    $rsf_ace_offsets_2015_A["civilite_offset"] = 11;
    $rsf_ace_offsets_2015_A["civilite_len"] = 1;
    $rsf_ace_offsets_2015_A["immatriculation_assure_offset"] = 12;
    $rsf_ace_offsets_2015_A["immatriculation_assure_len"] = 13;
    $rsf_ace_offsets_2015_A["cle_immatriculation_assure_offset"] = 25;
    $rsf_ace_offsets_2015_A["cle_immatriculation_assure_len"] = 2;
    $rsf_ace_offsets_2015_A["rang_beneficiaire_offset"] = 27;
    $rsf_ace_offsets_2015_A["rang_beneficiaire_len"] = 3;
    $rsf_ace_offsets_2015_A["no_facture_offset"] = 30;
    $rsf_ace_offsets_2015_A["no_facture_len"] = 9;
    $rsf_ace_offsets_2015_A["indicateur_parcours_soins_offset"] = 39;
    $rsf_ace_offsets_2015_A["indicateur_parcours_soins_len"] = 1;
    $rsf_ace_offsets_2015_A["nature_operation_offset"] = 40;
    $rsf_ace_offsets_2015_A["nature_operation_len"] = 1;
    $rsf_ace_offsets_2015_A["nature_assurance_offset"] = 41;
    $rsf_ace_offsets_2015_A["nature_assurance_len"] = 2;
    $rsf_ace_offsets_2015_A["justificatif_exo_offset"] = 43;
    $rsf_ace_offsets_2015_A["justificatif_exo_len"] = 1;
    $rsf_ace_offsets_2015_A["code_pec_offset"] = 44;
    $rsf_ace_offsets_2015_A["code_pec_len"] = 1;
    $rsf_ace_offsets_2015_A["motif_non_facturation_offset"] = 45;
    $rsf_ace_offsets_2015_A["motif_non_facturation_len"] = 1;
    $rsf_ace_offsets_2015_A["grand_regime_offset"] = 46;
    $rsf_ace_offsets_2015_A["grand_regime_len"] = 2;
    $rsf_ace_offsets_2015_A["date_naissance_offset"] = 48;
    $rsf_ace_offsets_2015_A["date_naissance_len"] = 8;
    $rsf_ace_offsets_2015_A["rang_naissance_offset"] = 56;
    $rsf_ace_offsets_2015_A["rang_naissance_len"] = 1;
    $rsf_ace_offsets_2015_A["date_entree_offset"] = 57;
    $rsf_ace_offsets_2015_A["date_entree_len"] = 8;
    $rsf_ace_offsets_2015_A["date_sortie_offset"] = 65;
    $rsf_ace_offsets_2015_A["date_sortie_len"] = 8;
    $rsf_ace_offsets_2015_A["code_postal_offset"] = 73;
    $rsf_ace_offsets_2015_A["code_postal_len"] = 5;
    $rsf_ace_offsets_2015_A["base_remboursement_c_offset"] = 78;
    $rsf_ace_offsets_2015_A["base_remboursement_c_len"] = 8;
    $rsf_ace_offsets_2015_A["total_remboursable_amo_offset"] = 86;
    $rsf_ace_offsets_2015_A["total_remboursable_amo_len"] = 8;
    $rsf_ace_offsets_2015_A["total_honoraires_factures_offset"] = 94;
    $rsf_ace_offsets_2015_A["total_honoraires_factures_len"] = 8;
    $rsf_ace_offsets_2015_A["total_honoraires_remboursable_offset"] = 102;
    $rsf_ace_offsets_2015_A["total_honoraires_remboursable_len"] = 8;
    $rsf_ace_offsets_2015_A["total_assure_avant_oc_offset"] = 110;
    $rsf_ace_offsets_2015_A["total_assure_avant_oc_len"] = 8;
    $rsf_ace_offsets_2015_A["total_remboursable_oc_ph_offset"] = 118;
    $rsf_ace_offsets_2015_A["total_remboursable_oc_ph_len"] = 8;
    $rsf_ace_offsets_2015_A["total_remboursable_oc_honoraires_offset"] = 126;
    $rsf_ace_offsets_2015_A["total_remboursable_oc_honoraires_len"] = 8;
    $rsf_ace_offsets_2015_A["total_facture_ph_offset"] = 134;
    $rsf_ace_offsets_2015_A["total_facture_ph_len"] = 8;
    $rsf_ace_offsets_2015_A["pat_benef_cmu_offset"] = 142;
    $rsf_ace_offsets_2015_A["pat_benef_cmu_len"] = 1;
    $rsf_ace_offsets_2015_A["valorise_fides_offset"] = 143;
    $rsf_ace_offsets_2015_A["valorise_fides_len"] = 1;
    $rsf_ace_offsets_2015_A["code_gestion_offset"] = 144;
    $rsf_ace_offsets_2015_A["code_gestion_len"] = 2;
    $rsf_ace_offsets_2015_A["no_organisme_complementaire_offset"] = 146;
    $rsf_ace_offsets_2015_A["no_organisme_complementaire_len"] = 10;
    $rsf_ace_offsets_2015_A["no_at_date_adc_offset"] = 156;
    $rsf_ace_offsets_2015_A["no_at_date_adc_len"] = 9;
    
    $rsf_ace_offsets_2009_A["finess_offset"] = 1;
    $rsf_ace_offsets_2009_A["finess_len"] = 9;
    $rsf_ace_offsets_2009_A["sexe_offset"] = 10;
    $rsf_ace_offsets_2009_A["sexe_len"] = 1;
    $rsf_ace_offsets_2009_A["civilite_offset"] = 11;
    $rsf_ace_offsets_2009_A["civilite_len"] = 1;
    $rsf_ace_offsets_2009_A["immatriculation_assure_offset"] = 12;
    $rsf_ace_offsets_2009_A["immatriculation_assure_len"] = 13;
    $rsf_ace_offsets_2009_A["cle_immatriculation_assure_offset"] = 25;
    $rsf_ace_offsets_2009_A["cle_immatriculation_assure_len"] = 2;
    $rsf_ace_offsets_2009_A["rang_beneficiaire_offset"] = 27;
    $rsf_ace_offsets_2009_A["rang_beneficiaire_len"] = 3;
    $rsf_ace_offsets_2009_A["no_facture_offset"] = 30;
    $rsf_ace_offsets_2009_A["no_facture_len"] = 9;
    $rsf_ace_offsets_2009_A["indicateur_parcours_soins_offset"] = 39;
    $rsf_ace_offsets_2009_A["indicateur_parcours_soins_len"] = 1;
    $rsf_ace_offsets_2009_A["nature_operation_offset"] = 40;
    $rsf_ace_offsets_2009_A["nature_operation_len"] = 1;
    $rsf_ace_offsets_2009_A["nature_assurance_offset"] = 41;
    $rsf_ace_offsets_2009_A["nature_assurance_len"] = 2;
    $rsf_ace_offsets_2009_A["justificatif_exo_offset"] = 43;
    $rsf_ace_offsets_2009_A["justificatif_exo_len"] = 1;
    $rsf_ace_offsets_2009_A["code_pec_offset"] = 44;
    $rsf_ace_offsets_2009_A["code_pec_len"] = 1;
    $rsf_ace_offsets_2009_A["motif_non_facturation_offset"] = 45;
    $rsf_ace_offsets_2009_A["motif_non_facturation_len"] = 1;
    $rsf_ace_offsets_2009_A["grand_regime_offset"] = 46;
    $rsf_ace_offsets_2009_A["grand_regime_len"] = 2;
    $rsf_ace_offsets_2009_A["date_naissance_offset"] = 48;
    $rsf_ace_offsets_2009_A["date_naissance_len"] = 8;
    $rsf_ace_offsets_2009_A["rang_naissance_offset"] = 56;
    $rsf_ace_offsets_2009_A["rang_naissance_len"] = 1;
    $rsf_ace_offsets_2009_A["date_entree_offset"] = 57;
    $rsf_ace_offsets_2009_A["date_entree_len"] = 8;
    $rsf_ace_offsets_2009_A["date_sortie_offset"] = 65;
    $rsf_ace_offsets_2009_A["date_sortie_len"] = 8;
    $rsf_ace_offsets_2009_A["code_postal_offset"] = 73;
    $rsf_ace_offsets_2009_A["code_postal_len"] = 5;
    $rsf_ace_offsets_2009_A["base_remboursement_c_offset"] = 78;
    $rsf_ace_offsets_2009_A["base_remboursement_c_len"] = 8;
    $rsf_ace_offsets_2009_A["total_remboursable_amo_offset"] = 86;
    $rsf_ace_offsets_2009_A["total_remboursable_amo_len"] = 8;
    $rsf_ace_offsets_2009_A["total_honoraires_factures_offset"] = 94;
    $rsf_ace_offsets_2009_A["total_honoraires_factures_len"] = 8;
    $rsf_ace_offsets_2009_A["total_honoraires_remboursable_offset"] = 102;
    $rsf_ace_offsets_2009_A["total_honoraires_remboursable_len"] = 8;
    $rsf_ace_offsets_2009_A["total_assure_avant_oc_offset"] = 110;
    $rsf_ace_offsets_2009_A["total_assure_avant_oc_len"] = 8;
    $rsf_ace_offsets_2009_A["total_remboursable_oc_ph_offset"] = 118;
    $rsf_ace_offsets_2009_A["total_remboursable_oc_ph_len"] = 8;
    $rsf_ace_offsets_2009_A["total_remboursable_oc_honoraires_offset"] = 126;
    $rsf_ace_offsets_2009_A["total_remboursable_oc_honoraires_len"] = 8;
    $rsf_ace_offsets_2009_A["total_facture_ph_offset"] = 134;
    $rsf_ace_offsets_2009_A["total_facture_ph_len"] = 8;
    $rsf_ace_offsets_2009_A["pat_benef_cmu_offset"] = 142;
    $rsf_ace_offsets_2009_A["pat_benef_cmu_len"] = 1;
    $rsf_ace_offsets_2009_A["valorise_fides_offset"] = 143;
    $rsf_ace_offsets_2009_A["valorise_fides_len"] = 1;
    
    $rsf_ace_offsets_2008_A["finess_offset"] = 1;
    $rsf_ace_offsets_2008_A["finess_len"] = 9;
    $rsf_ace_offsets_2008_A["sexe_offset"] = 10;
    $rsf_ace_offsets_2008_A["sexe_len"] = 1;
    $rsf_ace_offsets_2008_A["civilite_offset"] = 11;
    $rsf_ace_offsets_2008_A["civilite_len"] = 1;
    $rsf_ace_offsets_2008_A["immatriculation_assure_offset"] = 12;
    $rsf_ace_offsets_2008_A["immatriculation_assure_len"] = 13;
    $rsf_ace_offsets_2008_A["cle_immatriculation_assure_offset"] = 25;
    $rsf_ace_offsets_2008_A["cle_immatriculation_assure_len"] = 2;
    $rsf_ace_offsets_2008_A["rang_beneficiaire_offset"] = 27;
    $rsf_ace_offsets_2008_A["rang_beneficiaire_len"] = 3;
    $rsf_ace_offsets_2008_A["no_facture_offset"] = 30;
    $rsf_ace_offsets_2008_A["no_facture_len"] = 9;
    $rsf_ace_offsets_2008_A["indicateur_parcours_soins_offset"] = 39;
    $rsf_ace_offsets_2008_A["indicateur_parcours_soins_len"] = 1;
    $rsf_ace_offsets_2008_A["nature_operation_offset"] = 40;
    $rsf_ace_offsets_2008_A["nature_operation_len"] = 1;
    $rsf_ace_offsets_2008_A["nature_assurance_offset"] = 41;
    $rsf_ace_offsets_2008_A["nature_assurance_len"] = 2;
    $rsf_ace_offsets_2008_A["justificatif_exo_offset"] = 43;
    $rsf_ace_offsets_2008_A["justificatif_exo_len"] = 1;
    $rsf_ace_offsets_2008_A["code_pec_offset"] = 44;
    $rsf_ace_offsets_2008_A["code_pec_len"] = 1;
    $rsf_ace_offsets_2008_A["grand_regime_offset"] = 45;
    $rsf_ace_offsets_2008_A["grand_regime_len"] = 2;
    $rsf_ace_offsets_2008_A["date_naissance_offset"] = 47;
    $rsf_ace_offsets_2008_A["date_naissance_len"] = 8;
    $rsf_ace_offsets_2008_A["rang_naissance_offset"] = 55;
    $rsf_ace_offsets_2008_A["rang_naissance_len"] = 1;
    $rsf_ace_offsets_2008_A["date_entree_offset"] = 56;
    $rsf_ace_offsets_2008_A["date_entree_len"] = 8;
    $rsf_ace_offsets_2008_A["date_sortie_offset"] = 64;
    $rsf_ace_offsets_2008_A["date_sortie_len"] = 8;
    $rsf_ace_offsets_2008_A["base_remboursement_c_offset"] = 72;
    $rsf_ace_offsets_2008_A["base_remboursement_c_len"] = 8;
    $rsf_ace_offsets_2008_A["total_remboursable_amo_offset"] = 80;
    $rsf_ace_offsets_2008_A["total_remboursable_amo_len"] = 8;
    $rsf_ace_offsets_2008_A["total_honoraires_factures_offset"] = 88;
    $rsf_ace_offsets_2008_A["total_honoraires_factures_len"] = 8;
    $rsf_ace_offsets_2008_A["total_honoraires_remboursable_offset"] = 96;
    $rsf_ace_offsets_2008_A["total_honoraires_remboursable_len"] = 8;
    $rsf_ace_offsets_2008_A["total_assure_avant_oc_offset"] = 104;
    $rsf_ace_offsets_2008_A["total_assure_avant_oc_len"] = 8;
    $rsf_ace_offsets_2008_A["total_remboursable_oc_ph_offset"] = 112;
    $rsf_ace_offsets_2008_A["total_remboursable_oc_ph_len"] = 8;
    $rsf_ace_offsets_2008_A["total_remboursable_oc_honoraires_offset"] = 120;
    $rsf_ace_offsets_2008_A["total_remboursable_oc_honoraires_len"] = 8;
    $rsf_ace_offsets_2008_A["total_facture_ph_offset"] = 128;
    $rsf_ace_offsets_2008_A["total_facture_ph_len"] = 8;
    
    $rsf_ace_offsets_2007_A["finess_offset"] = 1;
    $rsf_ace_offsets_2007_A["finess_len"] = 9;
    $rsf_ace_offsets_2007_A["no_sejour_administratif_offset"] = 10;
    $rsf_ace_offsets_2007_A["no_sejour_administratif_len"] = 9;
    $rsf_ace_offsets_2007_A["sexe_offset"] = 19;
    $rsf_ace_offsets_2007_A["sexe_len"] = 1;
    $rsf_ace_offsets_2007_A["civilite_offset"] = 20;
    $rsf_ace_offsets_2007_A["civilite_len"] = 1;
    $rsf_ace_offsets_2007_A["immatriculation_assure_offset"] = 21;
    $rsf_ace_offsets_2007_A["immatriculation_assure_len"] = 13;
    $rsf_ace_offsets_2007_A["rang_beneficiaire_offset"] = 34;
    $rsf_ace_offsets_2007_A["rang_beneficiaire_len"] = 3;
    $rsf_ace_offsets_2007_A["nature_operation_offset"] = 37;
    $rsf_ace_offsets_2007_A["nature_operation_len"] = 1;
    $rsf_ace_offsets_2007_A["nature_assurance_offset"] = 38;
    $rsf_ace_offsets_2007_A["nature_assurance_len"] = 2;
    $rsf_ace_offsets_2007_A["justificatif_exo_offset"] = 40;
    $rsf_ace_offsets_2007_A["justificatif_exo_len"] = 1;
    $rsf_ace_offsets_2007_A["code_pec_offset"] = 41;
    $rsf_ace_offsets_2007_A["code_pec_len"] = 1;
    $rsf_ace_offsets_2007_A["no_facture_offset"] = 42;
    $rsf_ace_offsets_2007_A["no_facture_len"] = 9;
    $rsf_ace_offsets_2007_A["grand_regime_offset"] = 51;
    $rsf_ace_offsets_2007_A["grand_regime_len"] = 2;
    $rsf_ace_offsets_2007_A["date_naissance_offset"] = 53;
    $rsf_ace_offsets_2007_A["date_naissance_len"] = 8;
    $rsf_ace_offsets_2007_A["rang_naissance_offset"] = 61;
    $rsf_ace_offsets_2007_A["rang_naissance_len"] = 1;
    $rsf_ace_offsets_2007_A["date_entree_offset"] = 62;
    $rsf_ace_offsets_2007_A["date_entree_len"] = 8;
    $rsf_ace_offsets_2007_A["date_sortie_offset"] = 70;
    $rsf_ace_offsets_2007_A["date_sortie_len"] = 8;
    $rsf_ace_offsets_2007_A["base_remboursement_c_offset"] = 78;
    $rsf_ace_offsets_2007_A["base_remboursement_c_len"] = 8;
    $rsf_ace_offsets_2007_A["total_remboursable_amo_offset"] = 86;
    $rsf_ace_offsets_2007_A["total_remboursable_amo_len"] = 8;
    $rsf_ace_offsets_2007_A["total_honoraires_factures_offset"] = 94;
    $rsf_ace_offsets_2007_A["total_honoraires_factures_len"] = 8;
    $rsf_ace_offsets_2007_A["total_honoraires_remboursable_offset"] = 102;
    $rsf_ace_offsets_2007_A["total_honoraires_remboursable_len"] = 8;
    $rsf_ace_offsets_2007_A["total_assure_avant_oc_offset"] = 110;
    $rsf_ace_offsets_2007_A["total_assure_avant_oc_len"] = 8;
    $rsf_ace_offsets_2007_A["total_remboursable_oc_ph_offset"] = 118;
    $rsf_ace_offsets_2007_A["total_remboursable_oc_ph_len"] = 8;
    $rsf_ace_offsets_2007_A["total_remboursable_oc_honoraires_offset"] = 126;
    $rsf_ace_offsets_2007_A["total_remboursable_oc_honoraires_len"] = 8;
    $rsf_ace_offsets_2007_A["total_facture_ph_offset"] = 134;
    $rsf_ace_offsets_2007_A["total_facture_ph_len"] = 8;

    $rsf_ace_offsets_2016_B["finess_offset"] = 1;
    $rsf_ace_offsets_2016_B["finess_len"] = 9;
    $rsf_ace_offsets_2016_B["finess_geographique_offset"] = 10;
    $rsf_ace_offsets_2016_B["finess_geographique_len"] = 9;
    $rsf_ace_offsets_2016_B["immatriculation_assure_offset"] = 19;
    $rsf_ace_offsets_2016_B["immatriculation_assure_len"] = 13;
    $rsf_ace_offsets_2016_B["cle_immatriculation_assure_offset"] = 32;
    $rsf_ace_offsets_2016_B["cle_immatriculation_assure_len"] = 2;
    $rsf_ace_offsets_2016_B["rang_beneficiaire_offset"] = 34;
    $rsf_ace_offsets_2016_B["rang_beneficiaire_len"] = 3;
    $rsf_ace_offsets_2016_B["no_facture_offset"] = 37;
    $rsf_ace_offsets_2016_B["no_facture_len"] = 9;
    $rsf_ace_offsets_2016_B["mode_traitement_offset"] = 46;
    $rsf_ace_offsets_2016_B["mode_traitement_len"] = 2;
    $rsf_ace_offsets_2016_B["discpline_prestation_offset"] = 48;
    $rsf_ace_offsets_2016_B["discpline_prestation_len"] = 3;
    $rsf_ace_offsets_2016_B["justificatif_exo_offset"] = 51;
    $rsf_ace_offsets_2016_B["justificatif_exo_len"] = 1;
    $rsf_ace_offsets_2016_B["date_debut_offset"] = 54;
    $rsf_ace_offsets_2016_B["date_debut_len"] = 8;
    $rsf_ace_offsets_2016_B["date_fin_offset"] = 54;
    $rsf_ace_offsets_2016_B["date_fin_len"] = 8;
    $rsf_ace_offsets_2016_B["code_acte_offset"] = 62;
    $rsf_ace_offsets_2016_B["code_acte_len"] = 5;
    $rsf_ace_offsets_2016_B["nombre_offset"] = 67;
    $rsf_ace_offsets_2016_B["nombre_len"] = 3;
    $rsf_ace_offsets_2016_B["coefficient_offset"] = 70;
    $rsf_ace_offsets_2016_B["coefficient_len"] = 6;
    $rsf_ace_offsets_2016_B["denombrement_offset"] = 76;
    $rsf_ace_offsets_2016_B["denombrement_len"] = 1;
    $rsf_ace_offsets_2016_B["prix_unitaire_offset"] = 78;
    $rsf_ace_offsets_2016_B["prix_unitaire_len"] = 7;
    $rsf_ace_offsets_2016_B["base_remboursement_offset"] = 85;
    $rsf_ace_offsets_2016_B["base_remboursement_len"] = 8;
    $rsf_ace_offsets_2016_B["taux_offset"] = 93;
    $rsf_ace_offsets_2016_B["taux_len"] = 3;
    $rsf_ace_offsets_2016_B["montant_remboursable_offset"] = 96;
    $rsf_ace_offsets_2016_B["montant_remboursable_len"] = 8;
    $rsf_ace_offsets_2016_B["montant_total_depense_offset"] = 104;
    $rsf_ace_offsets_2016_B["montant_total_depense_len"] = 8;
    $rsf_ace_offsets_2016_B["montant_remboursable_oc_offset"] = 112;
    $rsf_ace_offsets_2016_B["montant_remboursable_oc_len"] = 7;

    $rsf_ace_offsets_2008_B["finess_offset"] = 1;
    $rsf_ace_offsets_2008_B["finess_len"] = 9;
    $rsf_ace_offsets_2008_B["immatriculation_assure_offset"] = 10;
    $rsf_ace_offsets_2008_B["immatriculation_assure_len"] = 13;
    $rsf_ace_offsets_2008_B["cle_immatriculation_assure_offset"] = 23;
    $rsf_ace_offsets_2008_B["cle_immatriculation_assure_len"] = 2;
    $rsf_ace_offsets_2008_B["rang_beneficiaire_offset"] = 25;
    $rsf_ace_offsets_2008_B["rang_beneficiaire_len"] = 3;
    $rsf_ace_offsets_2008_B["no_facture_offset"] = 28;
    $rsf_ace_offsets_2008_B["no_facture_len"] = 9;
    $rsf_ace_offsets_2008_B["mode_traitement_offset"] = 37;
    $rsf_ace_offsets_2008_B["mode_traitement_len"] = 2;
    $rsf_ace_offsets_2008_B["discpline_prestation_offset"] = 39;
    $rsf_ace_offsets_2008_B["discpline_prestation_len"] = 3;
    $rsf_ace_offsets_2008_B["justificatif_exo_offset"] = 42;
    $rsf_ace_offsets_2008_B["justificatif_exo_len"] = 1;
    $rsf_ace_offsets_2008_B["date_debut_offset"] = 45;
    $rsf_ace_offsets_2008_B["date_debut_len"] = 8;
    $rsf_ace_offsets_2008_B["date_fin_offset"] = 45;
    $rsf_ace_offsets_2008_B["date_fin_len"] = 8;
    $rsf_ace_offsets_2008_B["code_acte_offset"] = 53;
    $rsf_ace_offsets_2008_B["code_acte_len"] = 5;
    $rsf_ace_offsets_2008_B["nombre_offset"] = 58;
    $rsf_ace_offsets_2008_B["nombre_len"] = 3;
    $rsf_ace_offsets_2008_B["coefficient_offset"] = 61;
    $rsf_ace_offsets_2008_B["coefficient_len"] = 6;
    $rsf_ace_offsets_2008_B["denombrement_offset"] = 67;
    $rsf_ace_offsets_2008_B["denombrement_len"] = 1;
    $rsf_ace_offsets_2008_B["prix_unitaire_offset"] = 69;
    $rsf_ace_offsets_2008_B["prix_unitaire_len"] = 7;
    $rsf_ace_offsets_2008_B["base_remboursement_offset"] = 76;
    $rsf_ace_offsets_2008_B["base_remboursement_len"] = 8;
    $rsf_ace_offsets_2008_B["taux_offset"] = 84;
    $rsf_ace_offsets_2008_B["taux_len"] = 3;
    $rsf_ace_offsets_2008_B["montant_remboursable_offset"] = 87;
    $rsf_ace_offsets_2008_B["montant_remboursable_len"] = 8;
    $rsf_ace_offsets_2008_B["montant_total_depense_offset"] = 95;
    $rsf_ace_offsets_2008_B["montant_total_depense_len"] = 8;
    $rsf_ace_offsets_2008_B["montant_remboursable_oc_offset"] = 103;
    $rsf_ace_offsets_2008_B["montant_remboursable_oc_len"] = 7;
    
    $rsf_ace_offsets_2008_C["finess_offset"] = 1;
    $rsf_ace_offsets_2008_C["finess_len"] = 9;
    $rsf_ace_offsets_2008_C["immatriculation_assure_offset"] = 10;
    $rsf_ace_offsets_2008_C["immatriculation_assure_len"] = 13;
    $rsf_ace_offsets_2008_C["cle_immatriculation_assure_offset"] = 23;
    $rsf_ace_offsets_2008_C["cle_immatriculation_assure_len"] = 2;
    $rsf_ace_offsets_2008_C["rang_beneficiaire_offset"] = 25;
    $rsf_ace_offsets_2008_C["rang_beneficiaire_len"] = 3;
    $rsf_ace_offsets_2008_C["no_facture_offset"] = 28;
    $rsf_ace_offsets_2008_C["no_facture_len"] = 9;
    $rsf_ace_offsets_2008_C["mode_traitement_offset"] = 37;
    $rsf_ace_offsets_2008_C["mode_traitement_len"] = 2;
    $rsf_ace_offsets_2008_C["discpline_prestation_offset"] = 39;
    $rsf_ace_offsets_2008_C["discpline_prestation_len"] = 3;
    $rsf_ace_offsets_2008_C["justificatif_exo_offset"] = 42;
    $rsf_ace_offsets_2008_C["justificatif_exo_len"] = 1;
    $rsf_ace_offsets_2008_C["date_debut_offset"] = 45;
    $rsf_ace_offsets_2008_C["date_debut_len"] = 8;
    $rsf_ace_offsets_2008_C["date_fin_offset"] = 45;
    $rsf_ace_offsets_2008_C["date_fin_len"] = 8;
    $rsf_ace_offsets_2008_C["code_acte_offset"] = 53;
    $rsf_ace_offsets_2008_C["code_acte_len"] = 5;
    $rsf_ace_offsets_2008_C["nombre_offset"] = 58;
    $rsf_ace_offsets_2008_C["nombre_len"] = 3;
    $rsf_ace_offsets_2008_C["coefficient_offset"] = 61;
    $rsf_ace_offsets_2008_C["coefficient_len"] = 6;
    $rsf_ace_offsets_2008_C["denombrement_offset"] = 67;
    $rsf_ace_offsets_2008_C["denombrement_len"] = 1;
    $rsf_ace_offsets_2008_C["prix_unitaire_offset"] = 69;
    $rsf_ace_offsets_2008_C["prix_unitaire_len"] = 7;
    $rsf_ace_offsets_2008_C["base_remboursement_offset"] = 76;
    $rsf_ace_offsets_2008_C["base_remboursement_len"] = 8;
    $rsf_ace_offsets_2008_C["taux_offset"] = 84;
    $rsf_ace_offsets_2008_C["taux_len"] = 3;
    $rsf_ace_offsets_2008_C["montant_remboursable_offset"] = 87;
    $rsf_ace_offsets_2008_C["montant_remboursable_len"] = 8;
    $rsf_ace_offsets_2008_C["montant_total_depense_offset"] = 95;
    $rsf_ace_offsets_2008_C["montant_total_depense_len"] = 8;
    $rsf_ace_offsets_2008_C["montant_remboursable_oc_offset"] = 103;
    $rsf_ace_offsets_2008_C["montant_remboursable_oc_len"] = 7;

    $rsf_ace_offsets_2007_C["finess_offset"] = 1;
    $rsf_ace_offsets_2007_C["finess_len"] = 9;
    $rsf_ace_offsets_2007_C["immatriculation_assure_offset"] = 17;
    $rsf_ace_offsets_2007_C["immatriculation_assure_len"] = 13;
    $rsf_ace_offsets_2007_C["rang_beneficiaire_offset"] = 30;
    $rsf_ace_offsets_2007_C["rang_beneficiaire_len"] = 3;
    $rsf_ace_offsets_2007_C["mode_traitement_offset"] = 33;
    $rsf_ace_offsets_2007_C["mode_traitement_len"] = 2;
    $rsf_ace_offsets_2007_C["discpline_prestation_offset"] = 35;
    $rsf_ace_offsets_2007_C["discpline_prestation_len"] = 3;
    $rsf_ace_offsets_2007_C["date_acte_offset"] = 38;
    $rsf_ace_offsets_2007_C["date_acte_len"] = 8;
    $rsf_ace_offsets_2007_C["code_acte_offset"] = 47;
    $rsf_ace_offsets_2007_C["code_acte_len"] = 5;
    $rsf_ace_offsets_2007_C["nombre_offset"] = 52;
    $rsf_ace_offsets_2007_C["nombre_len"] = 2;
    $rsf_ace_offsets_2007_C["coefficient_offset"] = 54;
    $rsf_ace_offsets_2007_C["coefficient_len"] = 6;
    $rsf_ace_offsets_2007_C["denombrement_offset"] = 60;
    $rsf_ace_offsets_2007_C["denombrement_len"] = 2;
    $rsf_ace_offsets_2007_C["prix_unitaire_offset"] = 62;
    $rsf_ace_offsets_2007_C["prix_unitaire_len"] = 7;
    $rsf_ace_offsets_2007_C["base_remboursement_offset"] = 69;
    $rsf_ace_offsets_2007_C["base_remboursement_len"] = 7;
    $rsf_ace_offsets_2007_C["taux_offset"] = 76;
    $rsf_ace_offsets_2007_C["taux_len"] = 3;
    $rsf_ace_offsets_2007_C["montant_remboursable_offset"] = 79;
    $rsf_ace_offsets_2007_C["montant_remboursable_len"] = 7;
    $rsf_ace_offsets_2007_C["montant_total_depense_offset"] = 86;
    $rsf_ace_offsets_2007_C["montant_total_depense_len"] = 7;
    $rsf_ace_offsets_2007_C["montant_remboursable_oc_offset"] = 93;
    $rsf_ace_offsets_2007_C["montant_remboursable_oc_len"] = 7;
    
    $rsf_ace_offsets_2016_M["finess_offset"] = 1;
    $rsf_ace_offsets_2016_M["finess_len"] = 9;
    $rsf_ace_offsets_2016_M["finess_geographique_offset"] = 10;
    $rsf_ace_offsets_2016_M["finess_geographique_len"] = 9;
    $rsf_ace_offsets_2016_M["immatriculation_assure_offset"] = 19;
    $rsf_ace_offsets_2016_M["immatriculation_assure_len"] = 13;
    $rsf_ace_offsets_2016_M["cle_immatriculation_assure_offset"] = 32;
    $rsf_ace_offsets_2016_M["cle_immatriculation_assure_len"] = 2;
    $rsf_ace_offsets_2016_M["rang_beneficiaire_offset"] = 34;
    $rsf_ace_offsets_2016_M["rang_beneficiaire_len"] = 3;
    $rsf_ace_offsets_2016_M["no_facture_offset"] = 37;
    $rsf_ace_offsets_2016_M["no_facture_len"] = 9;
    $rsf_ace_offsets_2016_M["mode_traitement_offset"] = 46;
    $rsf_ace_offsets_2016_M["mode_traitement_len"] = 2;
    $rsf_ace_offsets_2016_M["discpline_prestation_offset"] = 48;
    $rsf_ace_offsets_2016_M["discpline_prestation_len"] = 3;
    $rsf_ace_offsets_2016_M["date_acte_offset"] = 51;
    $rsf_ace_offsets_2016_M["date_acte_len"] = 8;
    $rsf_ace_offsets_2016_M["code_acte_offset"] = 59;
    $rsf_ace_offsets_2016_M["code_acte_len"] = 7;
    $rsf_ace_offsets_2016_M["extension_ccam_offset"] = 72;
    $rsf_ace_offsets_2016_M["extension_ccam_len"] = 1;
    $rsf_ace_offsets_2016_M["activite_ccam_offset"] = 73;
    $rsf_ace_offsets_2016_M["activite_ccam_len"] = 1;
    $rsf_ace_offsets_2016_M["phase_ccam_offset"] = 74;
    $rsf_ace_offsets_2016_M["phase_ccam_len"] = 1;
    $rsf_ace_offsets_2016_M["modificateur_ccam_1_offset"] = 75;
    $rsf_ace_offsets_2016_M["modificateur_ccam_1_len"] = 1;
    $rsf_ace_offsets_2016_M["modificateur_ccam_2_offset"] = 76;
    $rsf_ace_offsets_2016_M["modificateur_ccam_2_len"] = 1;
    $rsf_ace_offsets_2016_M["modificateur_ccam_3_offset"] = 77;
    $rsf_ace_offsets_2016_M["modificateur_ccam_3_len"] = 1;
    $rsf_ace_offsets_2016_M["modificateur_ccam_4_offset"] = 78;
    $rsf_ace_offsets_2016_M["modificateur_ccam_4_len"] = 1;
    $rsf_ace_offsets_2016_M["association_nonprevue_ccam_offset"] = 79;
    $rsf_ace_offsets_2016_M["association_nonprevue_ccam_len"] = 1;
    $rsf_ace_offsets_2016_M["remboursement_excp_ccam_offset"] = 80;
    $rsf_ace_offsets_2016_M["remboursement_excp_ccam_len"] = 1;

    $rsf_ace_offsets_2008_M["finess_offset"] = 1;
    $rsf_ace_offsets_2008_M["finess_len"] = 9;
    $rsf_ace_offsets_2008_M["immatriculation_assure_offset"] = 10;
    $rsf_ace_offsets_2008_M["immatriculation_assure_len"] = 13;
    $rsf_ace_offsets_2008_M["cle_immatriculation_assure_offset"] = 23;
    $rsf_ace_offsets_2008_M["cle_immatriculation_assure_len"] = 2;
    $rsf_ace_offsets_2008_M["rang_beneficiaire_offset"] = 25;
    $rsf_ace_offsets_2008_M["rang_beneficiaire_len"] = 3;
    $rsf_ace_offsets_2008_M["no_facture_offset"] = 28;
    $rsf_ace_offsets_2008_M["no_facture_len"] = 9;
    $rsf_ace_offsets_2008_M["mode_traitement_offset"] = 37;
    $rsf_ace_offsets_2008_M["mode_traitement_len"] = 2;
    $rsf_ace_offsets_2008_M["discpline_prestation_offset"] = 39;
    $rsf_ace_offsets_2008_M["discpline_prestation_len"] = 3;
    $rsf_ace_offsets_2008_M["date_acte_offset"] = 42;
    $rsf_ace_offsets_2008_M["date_acte_len"] = 8;
    $rsf_ace_offsets_2008_M["code_acte_offset"] = 50;
    $rsf_ace_offsets_2008_M["code_acte_len"] = 7;
    $rsf_ace_offsets_2008_M["extension_ccam_offset"] = 63;
    $rsf_ace_offsets_2008_M["extension_ccam_len"] = 1;
    $rsf_ace_offsets_2008_M["activite_ccam_offset"] = 64;
    $rsf_ace_offsets_2008_M["activite_ccam_len"] = 1;
    $rsf_ace_offsets_2008_M["phase_ccam_offset"] = 65;
    $rsf_ace_offsets_2008_M["phase_ccam_len"] = 1;
    $rsf_ace_offsets_2008_M["modificateur_ccam_1_offset"] = 66;
    $rsf_ace_offsets_2008_M["modificateur_ccam_1_len"] = 1;
    $rsf_ace_offsets_2008_M["modificateur_ccam_2_offset"] = 67;
    $rsf_ace_offsets_2008_M["modificateur_ccam_2_len"] = 1;
    $rsf_ace_offsets_2008_M["modificateur_ccam_3_offset"] = 68;
    $rsf_ace_offsets_2008_M["modificateur_ccam_3_len"] = 1;
    $rsf_ace_offsets_2008_M["modificateur_ccam_4_offset"] = 69;
    $rsf_ace_offsets_2008_M["modificateur_ccam_4_len"] = 1;
    $rsf_ace_offsets_2008_M["association_nonprevue_ccam_offset"] = 70;
    $rsf_ace_offsets_2008_M["association_nonprevue_ccam_len"] = 1;
    $rsf_ace_offsets_2008_M["remboursement_excp_ccam_offset"] = 71;
    $rsf_ace_offsets_2008_M["remboursement_excp_ccam_len"] = 1;
    
    $rsf_ace_offsets_2007_M["finess_offset"] = 1;
    $rsf_ace_offsets_2007_M["finess_len"] = 9;
    $rsf_ace_offsets_2007_M["immatriculation_assure_offset"] = 17;
    $rsf_ace_offsets_2007_M["immatriculation_assure_len"] = 13;
    $rsf_ace_offsets_2007_M["rang_beneficiaire_offset"] = 30;
    $rsf_ace_offsets_2007_M["rang_beneficiaire_len"] = 3;
    $rsf_ace_offsets_2007_M["mode_traitement_offset"] = 33;
    $rsf_ace_offsets_2007_M["mode_traitement_len"] = 2;
    $rsf_ace_offsets_2007_M["discpline_prestation_offset"] = 35;
    $rsf_ace_offsets_2007_M["discpline_prestation_len"] = 3;
    $rsf_ace_offsets_2007_M["date_acte_offset"] = 38;
    $rsf_ace_offsets_2007_M["date_acte_len"] = 8;
    $rsf_ace_offsets_2007_M["code_acte_offset"] = 46;
    $rsf_ace_offsets_2007_M["code_acte_len"] = 7;
    $rsf_ace_offsets_2007_M["extension_ccam_offset"] = 59;
    $rsf_ace_offsets_2007_M["extension_ccam_len"] = 1;
    $rsf_ace_offsets_2007_M["activite_ccam_offset"] = 60;
    $rsf_ace_offsets_2007_M["activite_ccam_len"] = 1;
    $rsf_ace_offsets_2007_M["phase_ccam_offset"] = 61;
    $rsf_ace_offsets_2007_M["phase_ccam_len"] = 1;
    $rsf_ace_offsets_2007_M["modificateur_ccam_1_offset"] = 62;
    $rsf_ace_offsets_2007_M["modificateur_ccam_1_len"] = 1;
    $rsf_ace_offsets_2007_M["modificateur_ccam_2_offset"] = 63;
    $rsf_ace_offsets_2007_M["modificateur_ccam_2_len"] = 1;
    $rsf_ace_offsets_2007_M["modificateur_ccam_3_offset"] = 64;
    $rsf_ace_offsets_2007_M["modificateur_ccam_3_len"] = 1;
    $rsf_ace_offsets_2007_M["modificateur_ccam_4_offset"] = 65;
    $rsf_ace_offsets_2007_M["modificateur_ccam_4_len"] = 1;
    $rsf_ace_offsets_2007_M["association_nonprevue_ccam_offset"] = 66;
    $rsf_ace_offsets_2007_M["association_nonprevue_ccam_len"] = 1;
    $rsf_ace_offsets_2007_M["remboursement_excp_ccam_offset"] = 67;
    $rsf_ace_offsets_2007_M["remboursement_excp_ccam_len"] = 1;
    
    
    $fcp_dmi_offsets_2007 = array();
    $fcp_dmi_offsets_2008 = array();
    $fcp_ucd_offsets_2007 = array();
    $fcp_ucd_offsets_2008 = array();
    
    $fcp_dmi_offsets_2007["finess_offset"] = 0;
    $fcp_dmi_offsets_2007["finess_len"] = 9;
    $fcp_dmi_offsets_2007["no_sejour_administratif_offset"] = 9;
    $fcp_dmi_offsets_2007["no_sejour_administratif_len"] = 20;
    $fcp_dmi_offsets_2007["code_offset"] = 29;
    $fcp_dmi_offsets_2007["code_len"] = 9;
    $fcp_dmi_offsets_2007["nombre_offset"] = 38;
    $fcp_dmi_offsets_2007["nombre_len"] = 4;
    $fcp_dmi_offsets_2007["date_debut_offset"] = 42;
    $fcp_dmi_offsets_2007["date_debut_len"] = 8;

    $fcp_ucd_offsets_2007["finess_offset"] = 0;
    $fcp_ucd_offsets_2007["finess_len"] = 9;
    $fcp_ucd_offsets_2007["no_sejour_administratif_offset"] = 9;
    $fcp_ucd_offsets_2007["no_sejour_administratif_len"] = 20;
    $fcp_ucd_offsets_2007["code_offset"] = 29;
    $fcp_ucd_offsets_2007["code_len"] = 9;
    $fcp_ucd_offsets_2007["nombre_offset"] = 38;
    $fcp_ucd_offsets_2007["nombre_len"] = 7;
    $fcp_ucd_offsets_2007["date_debut_offset"] = 45;
    $fcp_ucd_offsets_2007["date_debut_len"] = 8;
    
    $fcp_dmi_offsets_2008["finess_offset"] = 0;
    $fcp_dmi_offsets_2008["finess_len"] = 9;
    $fcp_dmi_offsets_2008["type_prestation_offset"] = 9;
    $fcp_dmi_offsets_2008["type_prestation_len"] = 2;
    $fcp_dmi_offsets_2008["no_sejour_administratif_offset"] = 11;
    $fcp_dmi_offsets_2008["no_sejour_administratif_len"] = 20;
    $fcp_dmi_offsets_2008["no_rum_offset"] = 31;
    $fcp_dmi_offsets_2008["no_rum_len"] = 10;
    $fcp_dmi_offsets_2008["date_debut_offset"] = 41;
    $fcp_dmi_offsets_2008["date_debut_len"] = 8;
    $fcp_dmi_offsets_2008["date_fin_offset"] = 49;
    $fcp_dmi_offsets_2008["date_fin_len"] = 8;
    $fcp_dmi_offsets_2008["code_offset"] = 57;
    $fcp_dmi_offsets_2008["code_len"] = 15;
    $fcp_dmi_offsets_2008["nombre_offset"] = 72;
    $fcp_dmi_offsets_2008["nombre_len"] = 10;
    $fcp_dmi_offsets_2008["montant_paye_offset"] = 82;
    $fcp_dmi_offsets_2008["montant_paye_len"] = 10;
    
    $fcp_ucd_offsets_2008["finess_offset"] = 0;
    $fcp_ucd_offsets_2008["finess_len"] = 9;
    $fcp_ucd_offsets_2008["type_prestation_offset"] = 9;
    $fcp_ucd_offsets_2008["type_prestation_len"] = 2;
    $fcp_ucd_offsets_2008["no_sejour_administratif_offset"] = 11;
    $fcp_ucd_offsets_2008["no_sejour_administratif_len"] = 20;
    $fcp_ucd_offsets_2008["no_rum_offset"] = 31;
    $fcp_ucd_offsets_2008["no_rum_len"] = 10;
    $fcp_ucd_offsets_2008["date_debut_offset"] = 41;
    $fcp_ucd_offsets_2008["date_debut_len"] = 8;
    $fcp_ucd_offsets_2008["date_fin_offset"] = 49;
    $fcp_ucd_offsets_2008["date_fin_len"] = 8;
    $fcp_ucd_offsets_2008["code_offset"] = 57;
    $fcp_ucd_offsets_2008["code_len"] = 15;
    $fcp_ucd_offsets_2008["nombre_offset"] = 72;
    $fcp_ucd_offsets_2008["nombre_len"] = 10;
    $fcp_ucd_offsets_2008["montant_paye_offset"] = 82;
    $fcp_ucd_offsets_2008["montant_paye_len"] = 10;
    



    
    
    
    $rss_offsets_215 = array();
    
    $rsa_offsets_215["finess_offset"] = 0;
    $rsa_offsets_215["finess_len"] = 9;
    $rsa_offsets_215["version_format_rsa_offset"] = 9;
    $rsa_offsets_215["version_format_rsa_len"] = 3;
    $rsa_offsets_215["no_rsa_offset"] = 12;
    $rsa_offsets_215["no_rsa_len"] = 10;
    $rsa_offsets_215["version_format_offset"] = 22;
    $rsa_offsets_215["version_format_len"] = 3;
    $rsa_offsets_215["numero_tarif_offset"] = 25;
    $rsa_offsets_215["numero_tarif_len"] = 3;
    $rsa_offsets_215["version_groupage_offset"] = 28;
    $rsa_offsets_215["version_groupage_len"] = 2;
    $rsa_offsets_215["ghm_offset"] = 30;
    $rsa_offsets_215["ghm_len"] = 6;
    $rsa_offsets_215["code_retour_groupage_offset"] = 36;
    $rsa_offsets_215["code_retour_groupage_len"] = 3;
    $rsa_offsets_215["version_groupage_genrsa_offset"] = 39;
    $rsa_offsets_215["version_groupage_genrsa_len"] = 2;
    $rsa_offsets_215["ghm_genrsa_offset"] = 41;
    $rsa_offsets_215["ghm_genrsa_len"] = 6;
    $rsa_offsets_215["code_retour_groupage_genrsa_offset"] = 47;
    $rsa_offsets_215["code_retour_groupage_genrsa_len"] = 3;
    $rsa_offsets_215["nombre_rum_offset"] = 50;
    $rsa_offsets_215["nombre_rum_len"] = 2;
    $rsa_offsets_215["age_annees_offset"] = 52;
    $rsa_offsets_215["age_annees_len"] = 3;
    $rsa_offsets_215["age_jours_offset"] = 55;
    $rsa_offsets_215["age_jours_len"] = 3;
    $rsa_offsets_215["sexe_offset"] = 58;
    $rsa_offsets_215["sexe_len"] = 1;
    $rsa_offsets_215["mode_entree_offset"] = 59;
    $rsa_offsets_215["mode_entree_len"] = 1;
    $rsa_offsets_215["provenance_offset"] = 60;
    $rsa_offsets_215["provenance_len"] = 1;
    $rsa_offsets_215["mois_sortie_offset"] = 61;
    $rsa_offsets_215["mois_sortie_len"] = 6;
    $rsa_offsets_215["mode_sortie_offset"] = 67;
    $rsa_offsets_215["mode_sortie_len"] = 1;
    $rsa_offsets_215["destination_offset"] = 68;
    $rsa_offsets_215["destination_len"] = 1;
    $rsa_offsets_215["type_sejour_offset"] = 69;
    $rsa_offsets_215["type_sejour_len"] = 1;
    $rsa_offsets_215["duree_sejour_offset"] = 70;
    $rsa_offsets_215["duree_sejour_len"] = 4;
    $rsa_offsets_215["code_geographique_offset"] = 74;
    $rsa_offsets_215["code_geographique_len"] = 5;
    $rsa_offsets_215["poids_entree_offset"] = 79;
    $rsa_offsets_215["poids_entree_len"] = 4;
    $rsa_offsets_215["age_gestationnel_offset"] = 83;
    $rsa_offsets_215["age_gestationnel_len"] = 2;
    $rsa_offsets_215["nombre_seances_offset"] = 85;
    $rsa_offsets_215["nombre_seances_len"] = 2;
    $rsa_offsets_215["igs2_offset"] = 87;
    $rsa_offsets_215["igs2_len"] = 3;
    $rsa_offsets_215["ghs_genrsa_offset"] = 90;
    $rsa_offsets_215["ghs_genrsa_len"] = 4;
    $rsa_offsets_215["nombre_exh_offset"] = 94;
    $rsa_offsets_215["nombre_exh_len"] = 4;
    $rsa_offsets_215["exb_offset"] = 98;
    $rsa_offsets_215["exb_len"] = 1;

    $rss_offsets_222 = array();
    
    $rsa_offsets_222["finess_offset"] = 0;
    $rsa_offsets_222["finess_len"] = 9;
    $rsa_offsets_222["version_format_rsa_offset"] = 9;
    $rsa_offsets_222["version_format_rsa_len"] = 3;
    $rsa_offsets_222["no_rsa_offset"] = 12;
    $rsa_offsets_222["no_rsa_len"] = 10;
    $rsa_offsets_222["version_format_offset"] = 22;
    $rsa_offsets_222["version_format_len"] = 3;
    $rsa_offsets_222["numero_tarif_offset"] = 25;
    $rsa_offsets_222["numero_tarif_len"] = 3;
    $rsa_offsets_222["version_groupage_offset"] = 28;
    $rsa_offsets_222["version_groupage_len"] = 2;
    $rsa_offsets_222["ghm_offset"] = 30;
    $rsa_offsets_222["ghm_len"] = 6;
    $rsa_offsets_222["code_retour_groupage_offset"] = 36;
    $rsa_offsets_222["code_retour_groupage_len"] = 3;
    $rsa_offsets_222["version_groupage_genrsa_offset"] = 39;
    $rsa_offsets_222["version_groupage_genrsa_len"] = 2;
    $rsa_offsets_222["ghm_genrsa_offset"] = 41;
    $rsa_offsets_222["ghm_genrsa_len"] = 6;
    $rsa_offsets_222["code_retour_groupage_genrsa_offset"] = 47;
    $rsa_offsets_222["code_retour_groupage_genrsa_len"] = 3;
    $rsa_offsets_222["nombre_rum_offset"] = 50;
    $rsa_offsets_222["nombre_rum_len"] = 2;
    $rsa_offsets_222["age_annees_offset"] = 52;
    $rsa_offsets_222["age_annees_len"] = 3;
    $rsa_offsets_222["age_jours_offset"] = 55;
    $rsa_offsets_222["age_jours_len"] = 3;
    $rsa_offsets_222["sexe_offset"] = 58;
    $rsa_offsets_222["sexe_len"] = 1;
    $rsa_offsets_222["mode_entree_offset"] = 59;
    $rsa_offsets_222["mode_entree_len"] = 1;
    $rsa_offsets_222["provenance_offset"] = 60;
    $rsa_offsets_222["provenance_len"] = 1;
    $rsa_offsets_222["mois_sortie_offset"] = 61;
    $rsa_offsets_222["mois_sortie_len"] = 6;
    $rsa_offsets_222["mode_sortie_offset"] = 67;
    $rsa_offsets_222["mode_sortie_len"] = 1;
    $rsa_offsets_222["destination_offset"] = 68;
    $rsa_offsets_222["destination_len"] = 1;
    $rsa_offsets_222["type_sejour_offset"] = 69;
    $rsa_offsets_222["type_sejour_len"] = 1;
    $rsa_offsets_222["duree_sejour_offset"] = 70;
    $rsa_offsets_222["duree_sejour_len"] = 4;
    $rsa_offsets_222["code_geographique_offset"] = 74;
    $rsa_offsets_222["code_geographique_len"] = 5;
    $rsa_offsets_222["poids_entree_offset"] = 79;
    $rsa_offsets_222["poids_entree_len"] = 4;
    $rsa_offsets_222["age_gestationnel_offset"] = 83;
    $rsa_offsets_222["age_gestationnel_len"] = 2;
    $rsa_offsets_222["delai_dernieres_regles_offset"] = 85;
    $rsa_offsets_222["delai_dernieres_regles_len"] = 3;
    $rsa_offsets_222["nombre_seances_offset"] = 88;
    $rsa_offsets_222["nombre_seances_len"] = 2;
    $rsa_offsets_222["igs2_offset"] = 0;
    $rsa_offsets_222["igs2_len"] = 0;
    $rsa_offsets_222["ghs_genrsa_offset"] = 90;
    $rsa_offsets_222["ghs_genrsa_len"] = 4;
    $rsa_offsets_222["nombre_exh_offset"] = 94;
    $rsa_offsets_222["nombre_exh_len"] = 4;
    $rsa_offsets_222["type_exb_offset"] = 98;
    $rsa_offsets_222["type_exb_len"] = 1;
    $rsa_offsets_222["nb_exb_offset"] = 99;
    $rsa_offsets_222["nb_exb_len"] = 3;
    $rsa_offsets_222["top_uhcd_offset"] = 105;
    $rsa_offsets_222["top_uhcd_len"] = 1;
    $rsa_offsets_222["top_ghs_minore_offset"] = 106;
    $rsa_offsets_222["top_ghs_minore_len"] = 1;
    $rsa_offsets_222["confirmation_codage_offset"] = 107;
    $rsa_offsets_222["confirmation_codage_len"] = 1;
    $rsa_offsets_222["nb_aut_pgv_offset"] = 108;
    $rsa_offsets_222["nb_aut_pgv_len"] = 1;
    $rsa_offsets_222["nb_sup_dialyse_1_offset"] = 109;
    $rsa_offsets_222["nb_sup_dialyse_1_len"] = 3;
    $rsa_offsets_222["nb_sup_dialyse_2_offset"] = 112;
    $rsa_offsets_222["nb_sup_dialyse_2_len"] = 3;
    $rsa_offsets_222["nb_sup_dialyse_3_offset"] = 115;
    $rsa_offsets_222["nb_sup_dialyse_3_len"] = 3;
    $rsa_offsets_222["nb_sup_dialyse_4_offset"] = 118;
    $rsa_offsets_222["nb_sup_dialyse_4_len"] = 3;
    $rsa_offsets_222["nb_sup_apherese_offset"] = 121;
    $rsa_offsets_222["nb_sup_apherese_len"] = 3;
    $rsa_offsets_222["nb_sup_rap_offset"] = 124;
    $rsa_offsets_222["nb_sup_rap_len"] = 3;
    $rsa_offsets_222["nb_sup_ant_offset"] = 127;
    $rsa_offsets_222["nb_sup_ant_len"] = 3;
    $rsa_offsets_222["nb_rdth_offset"] = 130;
    $rsa_offsets_222["nb_rdth_len"] = 1;
    $rsa_offsets_222["top_valve_aortique_offset"] = 131;
    $rsa_offsets_222["top_valve_aortique_len"] = 1;
    $rsa_offsets_222["type_generation_automarique_offset"] = 132;
    $rsa_offsets_222["type_generation_automarique_len"] = 1;
    $rsa_offsets_222["nb_sup_hyperbare_offset"] = 145;
    $rsa_offsets_222["nb_sup_hyperbare_len"] = 3;
    $rsa_offsets_222["type_prestation_prelevement_organe_offset"] = 148;
    $rsa_offsets_222["type_prestation_prelevement_organe_len"] = 1;
    $rsa_offsets_222["nb_sup_rea_offset"] = 149;
    $rsa_offsets_222["nb_sup_rea_len"] = 3;
    $rsa_offsets_222["nb_sup_si_offset"] = 152;
    $rsa_offsets_222["nb_sup_si_len"] = 3;
    $rsa_offsets_222["nb_sup_stf_offset"] = 155;
    $rsa_offsets_222["nb_sup_stf_len"] = 3;
    $rsa_offsets_222["nb_sup_src_offset"] = 158;
    $rsa_offsets_222["nb_sup_src_len"] = 3;
    $rsa_offsets_222["nb_sup_nn1_offset"] = 161;
    $rsa_offsets_222["nb_sup_nn1_len"] = 3;
    $rsa_offsets_222["nb_sup_nn2_offset"] = 164;
    $rsa_offsets_222["nb_sup_nn2_len"] = 3;
    $rsa_offsets_222["nb_sup_nn3_offset"] = 167;
    $rsa_offsets_222["nb_sup_nn3_len"] = 3;
    $rsa_offsets_222["nb_sup_rep_offset"] = 170;
    $rsa_offsets_222["nb_sup_rep_len"] = 3;
    $rsa_offsets_222["passage_lit_sp_offset"] = 173;
    $rsa_offsets_222["passage_lit_sp_len"] = 1;
    $rsa_offsets_222["type_machine_rdth_offset"] = 174;
    $rsa_offsets_222["type_machine_rdth_len"] = 1;
    $rsa_offsets_222["type_dosimetrie_offset"] = 175;
    $rsa_offsets_222["type_dosimetrie_len"] = 1;
    $rsa_offsets_222["numero_innovation_offset"] = 176;
    $rsa_offsets_222["numero_innovation_len"] = 15;
    $rsa_offsets_222["nombre_ivg_anterieures_offset"] = 191;
    $rsa_offsets_222["nombre_ivg_anterieures_len"] = 2;
    $rsa_offsets_222["annee_ivg_precedente_offset"] = 193;
    $rsa_offsets_222["annee_ivg_precedente_len"] = 4;
    $rsa_offsets_222["nombre_naissances_vivantes_anterieures_offset"] = 197;
    $rsa_offsets_222["nombre_naissances_vivantes_anterieures_len"] = 2;
    $rsa_offsets_222["no_rum_dp_offset"] = 200;
    $rsa_offsets_222["no_rum_dp_len"] = 2;

    $rss_offsets_223 = array();
    
    $rsa_offsets_223["finess_offset"] = 0;
    $rsa_offsets_223["finess_len"] = 9;
    $rsa_offsets_223["version_format_rsa_offset"] = 9;
    $rsa_offsets_223["version_format_rsa_len"] = 3;
    $rsa_offsets_223["no_rsa_offset"] = 12;
    $rsa_offsets_223["no_rsa_len"] = 10;
    $rsa_offsets_223["version_format_offset"] = 22;
    $rsa_offsets_223["version_format_len"] = 3;
    $rsa_offsets_223["numero_tarif_offset"] = 25;
    $rsa_offsets_223["numero_tarif_len"] = 3;
    $rsa_offsets_223["version_groupage_offset"] = 28;
    $rsa_offsets_223["version_groupage_len"] = 2;
    $rsa_offsets_223["ghm_offset"] = 30;
    $rsa_offsets_223["ghm_len"] = 6;
    $rsa_offsets_223["code_retour_groupage_offset"] = 36;
    $rsa_offsets_223["code_retour_groupage_len"] = 3;
    $rsa_offsets_223["version_groupage_genrsa_offset"] = 39;
    $rsa_offsets_223["version_groupage_genrsa_len"] = 2;
    $rsa_offsets_223["ghm_genrsa_offset"] = 41;
    $rsa_offsets_223["ghm_genrsa_len"] = 6;
    $rsa_offsets_223["code_retour_groupage_genrsa_offset"] = 47;
    $rsa_offsets_223["code_retour_groupage_genrsa_len"] = 3;
    $rsa_offsets_223["nombre_rum_offset"] = 50;
    $rsa_offsets_223["nombre_rum_len"] = 2;
    $rsa_offsets_223["age_annees_offset"] = 52;
    $rsa_offsets_223["age_annees_len"] = 3;
    $rsa_offsets_223["age_jours_offset"] = 55;
    $rsa_offsets_223["age_jours_len"] = 3;
    $rsa_offsets_223["sexe_offset"] = 58;
    $rsa_offsets_223["sexe_len"] = 1;
    $rsa_offsets_223["mode_entree_offset"] = 59;
    $rsa_offsets_223["mode_entree_len"] = 1;
    $rsa_offsets_223["provenance_offset"] = 60;
    $rsa_offsets_223["provenance_len"] = 1;
    $rsa_offsets_223["mois_sortie_offset"] = 61;
    $rsa_offsets_223["mois_sortie_len"] = 6;
    $rsa_offsets_223["mode_sortie_offset"] = 67;
    $rsa_offsets_223["mode_sortie_len"] = 1;
    $rsa_offsets_223["destination_offset"] = 68;
    $rsa_offsets_223["destination_len"] = 1;
    $rsa_offsets_223["type_sejour_offset"] = 69;
    $rsa_offsets_223["type_sejour_len"] = 1;
    $rsa_offsets_223["duree_sejour_offset"] = 70;
    $rsa_offsets_223["duree_sejour_len"] = 4;
    $rsa_offsets_223["code_geographique_offset"] = 74;
    $rsa_offsets_223["code_geographique_len"] = 5;
    $rsa_offsets_223["poids_entree_offset"] = 79;
    $rsa_offsets_223["poids_entree_len"] = 4;
    $rsa_offsets_223["age_gestationnel_offset"] = 83;
    $rsa_offsets_223["age_gestationnel_len"] = 2;
    $rsa_offsets_223["delai_dernieres_regles_offset"] = 85;
    $rsa_offsets_223["delai_dernieres_regles_len"] = 3;
    $rsa_offsets_223["nombre_seances_offset"] = 88;
    $rsa_offsets_223["nombre_seances_len"] = 2;
    $rsa_offsets_223["igs2_offset"] = 0;
    $rsa_offsets_223["igs2_len"] = 0;
    $rsa_offsets_223["ghs_genrsa_offset"] = 90;
    $rsa_offsets_223["ghs_genrsa_len"] = 4;
    $rsa_offsets_223["nombre_exh_offset"] = 94;
    $rsa_offsets_223["nombre_exh_len"] = 4;
    $rsa_offsets_223["type_exb_offset"] = 98;
    $rsa_offsets_223["type_exb_len"] = 1;
    $rsa_offsets_223["nb_exb_offset"] = 99;
    $rsa_offsets_223["nb_exb_len"] = 3;
    $rsa_offsets_223["top_adm_maison_naissance_offset"] = 102;
    $rsa_offsets_223["top_adm_maison_naissance_len"] = 1;
    $rsa_offsets_223["top_radiation_part_avastin_offset"] = 103;
    $rsa_offsets_223["top_radiation_part_avastin_len"] = 1;
    $rsa_offsets_223["top_radiation_partielle_alimta_offset"] = 104;
    $rsa_offsets_223["top_radiation_partielle_alimta_len"] = 1;
    $rsa_offsets_223["top_uhcd_offset"] = 105;
    $rsa_offsets_223["top_uhcd_len"] = 1;
    $rsa_offsets_223["top_ghs_minore_offset"] = 106;
    $rsa_offsets_223["top_ghs_minore_len"] = 1;
    $rsa_offsets_223["confirmation_codage_offset"] = 107;
    $rsa_offsets_223["confirmation_codage_len"] = 1;
    $rsa_offsets_223["nb_aut_pgv_offset"] = 108;
    $rsa_offsets_223["nb_aut_pgv_len"] = 1;
    $rsa_offsets_223["nb_sup_dialyse_1_offset"] = 109;
    $rsa_offsets_223["nb_sup_dialyse_1_len"] = 3;
    $rsa_offsets_223["nb_sup_dialyse_2_offset"] = 112;
    $rsa_offsets_223["nb_sup_dialyse_2_len"] = 3;
    $rsa_offsets_223["nb_sup_dialyse_3_offset"] = 115;
    $rsa_offsets_223["nb_sup_dialyse_3_len"] = 3;
    $rsa_offsets_223["nb_sup_dialyse_4_offset"] = 118;
    $rsa_offsets_223["nb_sup_dialyse_4_len"] = 3;
    $rsa_offsets_223["nb_sup_apherese_offset"] = 121;
    $rsa_offsets_223["nb_sup_apherese_len"] = 3;
    $rsa_offsets_223["nb_sup_rap_offset"] = 124;
    $rsa_offsets_223["nb_sup_rap_len"] = 3;
    $rsa_offsets_223["nb_sup_ant_offset"] = 127;
    $rsa_offsets_223["nb_sup_ant_len"] = 3;
    $rsa_offsets_223["nb_rdth_offset"] = 130;
    $rsa_offsets_223["nb_rdth_len"] = 1;
    $rsa_offsets_223["top_valve_aortique_offset"] = 131;
    $rsa_offsets_223["top_valve_aortique_len"] = 1;
    $rsa_offsets_223["type_generation_automarique_offset"] = 132;
    $rsa_offsets_223["type_generation_automarique_len"] = 1;
    $rsa_offsets_223["nb_sup_hyperbare_offset"] = 145;
    $rsa_offsets_223["nb_sup_hyperbare_len"] = 3;
    $rsa_offsets_223["type_prestation_prelevement_organe_offset"] = 148;
    $rsa_offsets_223["type_prestation_prelevement_organe_len"] = 1;
    $rsa_offsets_223["nb_sup_rea_offset"] = 149;
    $rsa_offsets_223["nb_sup_rea_len"] = 3;
    $rsa_offsets_223["nb_sup_si_offset"] = 152;
    $rsa_offsets_223["nb_sup_si_len"] = 3;
    $rsa_offsets_223["nb_sup_stf_offset"] = 155;
    $rsa_offsets_223["nb_sup_stf_len"] = 3;
    $rsa_offsets_223["nb_sup_src_offset"] = 158;
    $rsa_offsets_223["nb_sup_src_len"] = 3;
    $rsa_offsets_223["nb_sup_nn1_offset"] = 161;
    $rsa_offsets_223["nb_sup_nn1_len"] = 3;
    $rsa_offsets_223["nb_sup_nn2_offset"] = 164;
    $rsa_offsets_223["nb_sup_nn2_len"] = 3;
    $rsa_offsets_223["nb_sup_nn3_offset"] = 167;
    $rsa_offsets_223["nb_sup_nn3_len"] = 3;
    $rsa_offsets_223["nb_sup_rep_offset"] = 170;
    $rsa_offsets_223["nb_sup_rep_len"] = 3;
    $rsa_offsets_223["passage_lit_sp_offset"] = 173;
    $rsa_offsets_223["passage_lit_sp_len"] = 1;
    $rsa_offsets_223["type_machine_rdth_offset"] = 174;
    $rsa_offsets_223["type_machine_rdth_len"] = 1;
    $rsa_offsets_223["type_dosimetrie_offset"] = 175;
    $rsa_offsets_223["type_dosimetrie_len"] = 1;
    $rsa_offsets_223["numero_innovation_offset"] = 176;
    $rsa_offsets_223["numero_innovation_len"] = 15;
    $rsa_offsets_223["nombre_ivg_anterieures_offset"] = 191;
    $rsa_offsets_223["nombre_ivg_anterieures_len"] = 2;
    $rsa_offsets_223["annee_ivg_precedente_offset"] = 193;
    $rsa_offsets_223["annee_ivg_precedente_len"] = 4;
    $rsa_offsets_223["nombre_naissances_vivantes_anterieures_offset"] = 197;
    $rsa_offsets_223["nombre_naissances_vivantes_anterieures_len"] = 2;
    $rsa_offsets_223["no_rum_dp_offset"] = 200;
    $rsa_offsets_223["no_rum_dp_len"] = 2;
	
	$rss_offsets_226 = array();
    
    $rsa_offsets_226["finess_offset"] = 0;
    $rsa_offsets_226["finess_len"] = 9;
    $rsa_offsets_226["version_format_rsa_offset"] = 9;
    $rsa_offsets_226["version_format_rsa_len"] = 3;
    $rsa_offsets_226["no_rsa_offset"] = 12;
    $rsa_offsets_226["no_rsa_len"] = 10;
    $rsa_offsets_226["version_format_offset"] = 22;
    $rsa_offsets_226["version_format_len"] = 3;
    $rsa_offsets_226["numero_tarif_offset"] = 25;
    $rsa_offsets_226["numero_tarif_len"] = 3;
    $rsa_offsets_226["version_groupage_offset"] = 28;
    $rsa_offsets_226["version_groupage_len"] = 2;
    $rsa_offsets_226["ghm_offset"] = 30;
    $rsa_offsets_226["ghm_len"] = 6;
    $rsa_offsets_226["code_retour_groupage_offset"] = 36;
    $rsa_offsets_226["code_retour_groupage_len"] = 3;
    $rsa_offsets_226["version_groupage_genrsa_offset"] = 39;
    $rsa_offsets_226["version_groupage_genrsa_len"] = 2;
    $rsa_offsets_226["ghm_genrsa_offset"] = 41;
    $rsa_offsets_226["ghm_genrsa_len"] = 6;
    $rsa_offsets_226["code_retour_groupage_genrsa_offset"] = 47;
    $rsa_offsets_226["code_retour_groupage_genrsa_len"] = 3;
    $rsa_offsets_226["nombre_rum_offset"] = 50;
    $rsa_offsets_226["nombre_rum_len"] = 2;
    $rsa_offsets_226["age_annees_offset"] = 52;
    $rsa_offsets_226["age_annees_len"] = 3;
    $rsa_offsets_226["age_jours_offset"] = 55;
    $rsa_offsets_226["age_jours_len"] = 3;
    $rsa_offsets_226["sexe_offset"] = 58;
    $rsa_offsets_226["sexe_len"] = 1;
    $rsa_offsets_226["mode_entree_offset"] = 59;
    $rsa_offsets_226["mode_entree_len"] = 1;
    $rsa_offsets_226["provenance_offset"] = 60;
    $rsa_offsets_226["provenance_len"] = 1;
    $rsa_offsets_226["mois_sortie_offset"] = 61;
    $rsa_offsets_226["mois_sortie_len"] = 6;
    $rsa_offsets_226["mode_sortie_offset"] = 67;
    $rsa_offsets_226["mode_sortie_len"] = 1;
    $rsa_offsets_226["destination_offset"] = 68;
    $rsa_offsets_226["destination_len"] = 1;
    $rsa_offsets_226["type_sejour_offset"] = 69;
    $rsa_offsets_226["type_sejour_len"] = 1;
    $rsa_offsets_226["duree_sejour_offset"] = 70;
    $rsa_offsets_226["duree_sejour_len"] = 4;
    $rsa_offsets_226["code_geographique_offset"] = 74;
    $rsa_offsets_226["code_geographique_len"] = 5;
    $rsa_offsets_226["poids_entree_offset"] = 79;
    $rsa_offsets_226["poids_entree_len"] = 4;
    $rsa_offsets_226["age_gestationnel_offset"] = 83;
    $rsa_offsets_226["age_gestationnel_len"] = 2;
    $rsa_offsets_226["delai_dernieres_regles_offset"] = 85;
    $rsa_offsets_226["delai_dernieres_regles_len"] = 3;
    $rsa_offsets_226["nombre_seances_offset"] = 93;
    $rsa_offsets_226["nombre_seances_len"] = 2;
    $rsa_offsets_226["igs2_offset"] = 0;
    $rsa_offsets_226["igs2_len"] = 0;
    $rsa_offsets_226["ghs_genrsa_offset"] = 95;
    $rsa_offsets_226["ghs_genrsa_len"] = 4;
    $rsa_offsets_226["nombre_exh_offset"] = 99;
    $rsa_offsets_226["nombre_exh_len"] = 4;
    $rsa_offsets_226["type_exb_offset"] = 103;
    $rsa_offsets_226["type_exb_len"] = 1;
    $rsa_offsets_226["nb_exb_offset"] = 104;
    $rsa_offsets_226["nb_exb_len"] = 3;
    $rsa_offsets_226["top_adm_maison_naissance_offset"] = 107;
    $rsa_offsets_226["top_adm_maison_naissance_len"] = 1;
    $rsa_offsets_226["top_radiation_part_avastin_offset"] = 108;
    $rsa_offsets_226["top_radiation_part_avastin_len"] = 1;
    $rsa_offsets_226["top_radiation_partielle_alimta_offset"] = 109;
    $rsa_offsets_226["top_radiation_partielle_alimta_len"] = 1;
    $rsa_offsets_226["top_uhcd_offset"] = 110;
    $rsa_offsets_226["top_uhcd_len"] = 1;
    $rsa_offsets_226["top_ghs_minore_offset"] = 111;
    $rsa_offsets_226["top_ghs_minore_len"] = 1;
    $rsa_offsets_226["confirmation_codage_offset"] = 112;
    $rsa_offsets_226["confirmation_codage_len"] = 1;
    $rsa_offsets_226["nb_aut_pgv_offset"] = 113;
    $rsa_offsets_226["nb_aut_pgv_len"] = 1;
    $rsa_offsets_226["nb_sup_dialyse_1_offset"] = 114;
    $rsa_offsets_226["nb_sup_dialyse_1_len"] = 3;
    $rsa_offsets_226["nb_sup_dialyse_2_offset"] = 117;
    $rsa_offsets_226["nb_sup_dialyse_2_len"] = 3;
    $rsa_offsets_226["nb_sup_dialyse_3_offset"] = 120;
    $rsa_offsets_226["nb_sup_dialyse_3_len"] = 3;
    $rsa_offsets_226["nb_sup_dialyse_4_offset"] = 123;
    $rsa_offsets_226["nb_sup_dialyse_4_len"] = 3;
    $rsa_offsets_226["nb_sup_apherese_offset"] = 126;
    $rsa_offsets_226["nb_sup_apherese_len"] = 3;
    $rsa_offsets_226["nb_sup_rap_offset"] = 129;
    $rsa_offsets_226["nb_sup_rap_len"] = 3;
    $rsa_offsets_226["nb_sup_ant_offset"] = 132;
    $rsa_offsets_226["nb_sup_ant_len"] = 3;
    $rsa_offsets_226["nb_rdth_offset"] = 135;
    $rsa_offsets_226["nb_rdth_len"] = 1;
    $rsa_offsets_226["top_valve_aortique_offset"] = 136;
    $rsa_offsets_226["top_valve_aortique_len"] = 1;
    $rsa_offsets_226["type_generation_automarique_offset"] = 137;
    $rsa_offsets_226["type_generation_automarique_len"] = 1;
    $rsa_offsets_226["nb_sup_hyperbare_offset"] = 145;
    $rsa_offsets_226["nb_sup_hyperbare_len"] = 3;
    $rsa_offsets_226["type_prestation_prelevement_organe_offset"] = 153;
    $rsa_offsets_226["type_prestation_prelevement_organe_len"] = 1;
    $rsa_offsets_226["nb_sup_rea_offset"] = 154;
    $rsa_offsets_226["nb_sup_rea_len"] = 3;
    $rsa_offsets_226["nb_sup_si_offset"] = 157;
    $rsa_offsets_226["nb_sup_si_len"] = 3;
    $rsa_offsets_226["nb_sup_stf_offset"] = 160;
    $rsa_offsets_226["nb_sup_stf_len"] = 3;
    $rsa_offsets_226["nb_sup_src_offset"] = 163;
    $rsa_offsets_226["nb_sup_src_len"] = 3;
    $rsa_offsets_226["nb_sup_nn1_offset"] = 166;
    $rsa_offsets_226["nb_sup_nn1_len"] = 3;
    $rsa_offsets_226["nb_sup_nn2_offset"] = 169;
    $rsa_offsets_226["nb_sup_nn2_len"] = 3;
    $rsa_offsets_226["nb_sup_nn3_offset"] = 172;
    $rsa_offsets_226["nb_sup_nn3_len"] = 3;
    $rsa_offsets_226["nb_sup_rep_offset"] = 175;
    $rsa_offsets_226["nb_sup_rep_len"] = 3;
    $rsa_offsets_226["passage_lit_sp_offset"] = 178;
    $rsa_offsets_226["passage_lit_sp_len"] = 1;
    $rsa_offsets_226["type_machine_rdth_offset"] = 179;
    $rsa_offsets_226["type_machine_rdth_len"] = 1;
    $rsa_offsets_226["type_dosimetrie_offset"] = 180;
    $rsa_offsets_226["type_dosimetrie_len"] = 1;
    $rsa_offsets_226["numero_innovation_offset"] = 181;
    $rsa_offsets_226["numero_innovation_len"] = 15;
    $rsa_offsets_226["nombre_ivg_anterieures_offset"] = 196;
    $rsa_offsets_226["nombre_ivg_anterieures_len"] = 2;
    $rsa_offsets_226["annee_ivg_precedente_offset"] = 203;
    $rsa_offsets_226["annee_ivg_precedente_len"] = 4;
    $rsa_offsets_226["nombre_naissances_vivantes_anterieures_offset"] = 205;
    $rsa_offsets_226["nombre_naissances_vivantes_anterieures_len"] = 2;
    $rsa_offsets_226["no_rum_dp_offset"] = 209;
    $rsa_offsets_226["no_rum_dp_len"] = 2;
	
	
	$rss_offsets_227 = array();
    
    $rsa_offsets_227["finess_offset"] = 0;
    $rsa_offsets_227["finess_len"] = 9;
    $rsa_offsets_227["version_format_rsa_offset"] = 9;
    $rsa_offsets_227["version_format_rsa_len"] = 3;
    $rsa_offsets_227["no_rsa_offset"] = 12;
    $rsa_offsets_227["no_rsa_len"] = 10;
    $rsa_offsets_227["version_format_offset"] = 22;
    $rsa_offsets_227["version_format_len"] = 3;
    $rsa_offsets_227["numero_tarif_offset"] = 25;
    $rsa_offsets_227["numero_tarif_len"] = 3;
    $rsa_offsets_227["version_groupage_offset"] = 28;
    $rsa_offsets_227["version_groupage_len"] = 2;
    $rsa_offsets_227["ghm_offset"] = 30;
    $rsa_offsets_227["ghm_len"] = 6;
    $rsa_offsets_227["code_retour_groupage_offset"] = 36;
    $rsa_offsets_227["code_retour_groupage_len"] = 3;
    $rsa_offsets_227["version_groupage_genrsa_offset"] = 39;
    $rsa_offsets_227["version_groupage_genrsa_len"] = 2;
    $rsa_offsets_227["ghm_genrsa_offset"] = 41;
    $rsa_offsets_227["ghm_genrsa_len"] = 6;
    $rsa_offsets_227["code_retour_groupage_genrsa_offset"] = 47;
    $rsa_offsets_227["code_retour_groupage_genrsa_len"] = 3;
    $rsa_offsets_227["nombre_rum_offset"] = 50;
    $rsa_offsets_227["nombre_rum_len"] = 2;
    $rsa_offsets_227["age_annees_offset"] = 52;
    $rsa_offsets_227["age_annees_len"] = 3;
    $rsa_offsets_227["age_jours_offset"] = 55;
    $rsa_offsets_227["age_jours_len"] = 3;
    $rsa_offsets_227["sexe_offset"] = 58;
    $rsa_offsets_227["sexe_len"] = 1;
    $rsa_offsets_227["mode_entree_offset"] = 59;
    $rsa_offsets_227["mode_entree_len"] = 1;
    $rsa_offsets_227["provenance_offset"] = 60;
    $rsa_offsets_227["provenance_len"] = 1;
    $rsa_offsets_227["mois_sortie_offset"] = 61;
    $rsa_offsets_227["mois_sortie_len"] = 6;
    $rsa_offsets_227["mode_sortie_offset"] = 67;
    $rsa_offsets_227["mode_sortie_len"] = 1;
    $rsa_offsets_227["destination_offset"] = 68;
    $rsa_offsets_227["destination_len"] = 1;
    $rsa_offsets_227["type_sejour_offset"] = 69;
    $rsa_offsets_227["type_sejour_len"] = 1;
    $rsa_offsets_227["duree_sejour_offset"] = 70;
    $rsa_offsets_227["duree_sejour_len"] = 4;
    $rsa_offsets_227["code_geographique_offset"] = 74;
    $rsa_offsets_227["code_geographique_len"] = 5;
    $rsa_offsets_227["poids_entree_offset"] = 79;
    $rsa_offsets_227["poids_entree_len"] = 4;
    $rsa_offsets_227["age_gestationnel_offset"] = 83;
    $rsa_offsets_227["age_gestationnel_len"] = 2;
    $rsa_offsets_227["delai_dernieres_regles_offset"] = 85;
    $rsa_offsets_227["delai_dernieres_regles_len"] = 3;
    $rsa_offsets_227["nombre_seances_offset"] = 93;
    $rsa_offsets_227["nombre_seances_len"] = 2;
    $rsa_offsets_227["igs2_offset"] = 0;
    $rsa_offsets_227["igs2_len"] = 0;
    $rsa_offsets_227["ghs_genrsa_offset"] = 95;
    $rsa_offsets_227["ghs_genrsa_len"] = 4;
    $rsa_offsets_227["nombre_exh_offset"] = 99;
    $rsa_offsets_227["nombre_exh_len"] = 4;
    $rsa_offsets_227["type_exb_offset"] = 103;
    $rsa_offsets_227["type_exb_len"] = 1;
    $rsa_offsets_227["nb_exb_offset"] = 104;
    $rsa_offsets_227["nb_exb_len"] = 3;
    $rsa_offsets_227["top_adm_maison_naissance_offset"] = 107;
    $rsa_offsets_227["top_adm_maison_naissance_len"] = 1;
    $rsa_offsets_227["top_radiation_part_avastin_offset"] = 108;
    $rsa_offsets_227["top_radiation_part_avastin_len"] = 1;
    $rsa_offsets_227["top_radiation_partielle_alimta_offset"] = 109;
    $rsa_offsets_227["top_radiation_partielle_alimta_len"] = 1;
    $rsa_offsets_227["top_uhcd_offset"] = 110;
    $rsa_offsets_227["top_uhcd_len"] = 1;
    $rsa_offsets_227["top_ghs_minore_offset"] = 111;
    $rsa_offsets_227["top_ghs_minore_len"] = 1;
    $rsa_offsets_227["confirmation_codage_offset"] = 112;
    $rsa_offsets_227["confirmation_codage_len"] = 1;
    $rsa_offsets_227["nb_aut_pgv_offset"] = 113;
    $rsa_offsets_227["nb_aut_pgv_len"] = 1;
    $rsa_offsets_227["nb_sup_dialyse_1_offset"] = 114;
    $rsa_offsets_227["nb_sup_dialyse_1_len"] = 3;
    $rsa_offsets_227["nb_sup_dialyse_2_offset"] = 117;
    $rsa_offsets_227["nb_sup_dialyse_2_len"] = 3;
    $rsa_offsets_227["nb_sup_dialyse_3_offset"] = 120;
    $rsa_offsets_227["nb_sup_dialyse_3_len"] = 3;
    $rsa_offsets_227["nb_sup_dialyse_4_offset"] = 123;
    $rsa_offsets_227["nb_sup_dialyse_4_len"] = 3;
    $rsa_offsets_227["nb_sup_apherese_offset"] = 126;
    $rsa_offsets_227["nb_sup_apherese_len"] = 3;
    $rsa_offsets_227["nb_sup_rap_offset"] = 129;
    $rsa_offsets_227["nb_sup_rap_len"] = 3;
    $rsa_offsets_227["nb_sup_ant_offset"] = 132;
    $rsa_offsets_227["nb_sup_ant_len"] = 3;
    $rsa_offsets_227["nb_rdth_offset"] = 135;
    $rsa_offsets_227["nb_rdth_len"] = 1;
    $rsa_offsets_227["top_valve_aortique_offset"] = 136;
    $rsa_offsets_227["top_valve_aortique_len"] = 1;
    $rsa_offsets_227["type_generation_automarique_offset"] = 137;
    $rsa_offsets_227["type_generation_automarique_len"] = 1;
    $rsa_offsets_227["nb_sup_hyperbare_offset"] = 145;
    $rsa_offsets_227["nb_sup_hyperbare_len"] = 3;
    $rsa_offsets_227["type_prestation_prelevement_organe_offset"] = 153;
    $rsa_offsets_227["type_prestation_prelevement_organe_len"] = 1;
    $rsa_offsets_227["nb_sup_rea_offset"] = 154;
    $rsa_offsets_227["nb_sup_rea_len"] = 3;
    $rsa_offsets_227["nb_sup_si_offset"] = 157;
    $rsa_offsets_227["nb_sup_si_len"] = 3;
    $rsa_offsets_227["nb_sup_stf_offset"] = 160;
    $rsa_offsets_227["nb_sup_stf_len"] = 3;
    $rsa_offsets_227["nb_sup_src_offset"] = 163;
    $rsa_offsets_227["nb_sup_src_len"] = 3;
    $rsa_offsets_227["nb_sup_nn1_offset"] = 166;
    $rsa_offsets_227["nb_sup_nn1_len"] = 3;
    $rsa_offsets_227["nb_sup_nn2_offset"] = 169;
    $rsa_offsets_227["nb_sup_nn2_len"] = 3;
    $rsa_offsets_227["nb_sup_nn3_offset"] = 172;
    $rsa_offsets_227["nb_sup_nn3_len"] = 3;
    $rsa_offsets_227["nb_sup_rep_offset"] = 175;
    $rsa_offsets_227["nb_sup_rep_len"] = 3;
    $rsa_offsets_227["passage_lit_sp_offset"] = 178;
    $rsa_offsets_227["passage_lit_sp_len"] = 1;
    $rsa_offsets_227["type_machine_rdth_offset"] = 179;
    $rsa_offsets_227["type_machine_rdth_len"] = 1;
    $rsa_offsets_227["type_dosimetrie_offset"] = 180;
    $rsa_offsets_227["type_dosimetrie_len"] = 1;
    $rsa_offsets_227["numero_innovation_offset"] = 181;
    $rsa_offsets_227["numero_innovation_len"] = 15;
    $rsa_offsets_227["nombre_ivg_anterieures_offset"] = 196;
    $rsa_offsets_227["nombre_ivg_anterieures_len"] = 2;
    $rsa_offsets_227["annee_ivg_precedente_offset"] = 203;
    $rsa_offsets_227["annee_ivg_precedente_len"] = 4;
    $rsa_offsets_227["nombre_naissances_vivantes_anterieures_offset"] = 205;
    $rsa_offsets_227["nombre_naissances_vivantes_anterieures_len"] = 2;
    $rsa_offsets_227["no_rum_dp_offset"] = 209;
    $rsa_offsets_227["no_rum_dp_len"] = 2;	$rss_offsets_227 = array();

    $rss_offsets_228 = array();

    $rsa_offsets_228["finess_offset"] = 0;
    $rsa_offsets_228["finess_len"] = 9;
    $rsa_offsets_228["version_format_rsa_offset"] = 9;
    $rsa_offsets_228["version_format_rsa_len"] = 3;
    $rsa_offsets_228["no_rsa_offset"] = 12;
    $rsa_offsets_228["no_rsa_len"] = 10;
    $rsa_offsets_228["version_format_offset"] = 22;
    $rsa_offsets_228["version_format_len"] = 3;
    $rsa_offsets_228["numero_tarif_offset"] = 25;
    $rsa_offsets_228["numero_tarif_len"] = 3;
    $rsa_offsets_228["version_groupage_offset"] = 28;
    $rsa_offsets_228["version_groupage_len"] = 2;
    $rsa_offsets_228["ghm_offset"] = 30;
    $rsa_offsets_228["ghm_len"] = 6;
    $rsa_offsets_228["code_retour_groupage_offset"] = 36;
    $rsa_offsets_228["code_retour_groupage_len"] = 3;
    $rsa_offsets_228["version_groupage_genrsa_offset"] = 39;
    $rsa_offsets_228["version_groupage_genrsa_len"] = 2;
    $rsa_offsets_228["ghm_genrsa_offset"] = 41;
    $rsa_offsets_228["ghm_genrsa_len"] = 6;
    $rsa_offsets_228["code_retour_groupage_genrsa_offset"] = 47;
    $rsa_offsets_228["code_retour_groupage_genrsa_len"] = 3;
    $rsa_offsets_228["nombre_rum_offset"] = 50;
    $rsa_offsets_228["nombre_rum_len"] = 2;
    $rsa_offsets_228["age_annees_offset"] = 52;
    $rsa_offsets_228["age_annees_len"] = 3;
    $rsa_offsets_228["age_jours_offset"] = 55;
    $rsa_offsets_228["age_jours_len"] = 3;
    $rsa_offsets_228["sexe_offset"] = 58;
    $rsa_offsets_228["sexe_len"] = 1;
    $rsa_offsets_228["mode_entree_offset"] = 59;
    $rsa_offsets_228["mode_entree_len"] = 1;
    $rsa_offsets_228["provenance_offset"] = 60;
    $rsa_offsets_228["provenance_len"] = 1;
    $rsa_offsets_228["mois_sortie_offset"] = 61;
    $rsa_offsets_228["mois_sortie_len"] = 6;
    $rsa_offsets_228["mode_sortie_offset"] = 67;
    $rsa_offsets_228["mode_sortie_len"] = 1;
    $rsa_offsets_228["destination_offset"] = 68;
    $rsa_offsets_228["destination_len"] = 1;
    $rsa_offsets_228["type_sejour_offset"] = 69;
    $rsa_offsets_228["type_sejour_len"] = 1;
    $rsa_offsets_228["duree_sejour_offset"] = 70;
    $rsa_offsets_228["duree_sejour_len"] = 4;
    $rsa_offsets_228["code_geographique_offset"] = 74;
    $rsa_offsets_228["code_geographique_len"] = 5;
    $rsa_offsets_228["poids_entree_offset"] = 79;
    $rsa_offsets_228["poids_entree_len"] = 4;
    $rsa_offsets_228["age_gestationnel_offset"] = 83;
    $rsa_offsets_228["age_gestationnel_len"] = 2;
    $rsa_offsets_228["delai_dernieres_regles_offset"] = 85;
    $rsa_offsets_228["delai_dernieres_regles_len"] = 3;
    $rsa_offsets_228["nombre_seances_offset"] = 93;
    $rsa_offsets_228["nombre_seances_len"] = 2;
    $rsa_offsets_228["igs2_offset"] = 0;
    $rsa_offsets_228["igs2_len"] = 0;
    $rsa_offsets_228["ghs_genrsa_offset"] = 95;
    $rsa_offsets_228["ghs_genrsa_len"] = 4;
    $rsa_offsets_228["nombre_exh_offset"] = 99;
    $rsa_offsets_228["nombre_exh_len"] = 4;
    $rsa_offsets_228["type_exb_offset"] = 103;
    $rsa_offsets_228["type_exb_len"] = 1;
    $rsa_offsets_228["nb_exb_offset"] = 104;
    $rsa_offsets_228["nb_exb_len"] = 3;
    $rsa_offsets_228["top_adm_maison_naissance_offset"] = 107;
    $rsa_offsets_228["top_adm_maison_naissance_len"] = 1;
    $rsa_offsets_228["top_radiation_part_avastin_offset"] = 108;
    $rsa_offsets_228["top_radiation_part_avastin_len"] = 1;
    $rsa_offsets_228["top_radiation_partielle_alimta_offset"] = 109;
    $rsa_offsets_228["top_radiation_partielle_alimta_len"] = 1;
    $rsa_offsets_228["top_uhcd_offset"] = 110;
    $rsa_offsets_228["top_uhcd_len"] = 1;
    $rsa_offsets_228["top_ghs_minore_offset"] = 111;
    $rsa_offsets_228["top_ghs_minore_len"] = 1;
    $rsa_offsets_228["confirmation_codage_offset"] = 112;
    $rsa_offsets_228["confirmation_codage_len"] = 1;
    $rsa_offsets_228["nb_aut_pgv_offset"] = 113;
    $rsa_offsets_228["nb_aut_pgv_len"] = 1;
    $rsa_offsets_228["nb_sup_dialyse_1_offset"] = 114;
    $rsa_offsets_228["nb_sup_dialyse_1_len"] = 3;
    $rsa_offsets_228["nb_sup_dialyse_2_offset"] = 117;
    $rsa_offsets_228["nb_sup_dialyse_2_len"] = 3;
    $rsa_offsets_228["nb_sup_dialyse_3_offset"] = 120;
    $rsa_offsets_228["nb_sup_dialyse_3_len"] = 3;
    $rsa_offsets_228["nb_sup_dialyse_4_offset"] = 123;
    $rsa_offsets_228["nb_sup_dialyse_4_len"] = 3;
    $rsa_offsets_228["nb_sup_apherese_offset"] = 126;
    $rsa_offsets_228["nb_sup_apherese_len"] = 3;
    $rsa_offsets_228["nb_sup_rap_offset"] = 129;
    $rsa_offsets_228["nb_sup_rap_len"] = 3;
    $rsa_offsets_228["nb_sup_ant_offset"] = 132;
    $rsa_offsets_228["nb_sup_ant_len"] = 3;
    $rsa_offsets_228["nb_rdth_offset"] = 135;
    $rsa_offsets_228["nb_rdth_len"] = 1;
    $rsa_offsets_228["top_valve_aortique_offset"] = 136;
    $rsa_offsets_228["top_valve_aortique_len"] = 1;
    $rsa_offsets_228["type_generation_automarique_offset"] = 137;
    $rsa_offsets_228["type_generation_automarique_len"] = 1;
    $rsa_offsets_228["nb_sup_hyperbare_offset"] = 145;
    $rsa_offsets_228["nb_sup_hyperbare_len"] = 3;
    $rsa_offsets_228["type_prestation_prelevement_organe_offset"] = 153;
    $rsa_offsets_228["type_prestation_prelevement_organe_len"] = 1;
    $rsa_offsets_228["nb_sup_rea_offset"] = 154;
    $rsa_offsets_228["nb_sup_rea_len"] = 3;
    $rsa_offsets_228["nb_sup_si_offset"] = 157;
    $rsa_offsets_228["nb_sup_si_len"] = 3;
    $rsa_offsets_228["nb_sup_stf_offset"] = 160;
    $rsa_offsets_228["nb_sup_stf_len"] = 3;
    $rsa_offsets_228["nb_sup_src_offset"] = 163;
    $rsa_offsets_228["nb_sup_src_len"] = 3;
    $rsa_offsets_228["nb_sup_nn1_offset"] = 166;
    $rsa_offsets_228["nb_sup_nn1_len"] = 3;
    $rsa_offsets_228["nb_sup_nn2_offset"] = 169;
    $rsa_offsets_228["nb_sup_nn2_len"] = 3;
    $rsa_offsets_228["nb_sup_nn3_offset"] = 172;
    $rsa_offsets_228["nb_sup_nn3_len"] = 3;
    $rsa_offsets_228["nb_sup_rep_offset"] = 175;
    $rsa_offsets_228["nb_sup_rep_len"] = 3;
    $rsa_offsets_228["passage_lit_sp_offset"] = 178;
    $rsa_offsets_228["passage_lit_sp_len"] = 1;
    $rsa_offsets_228["type_machine_rdth_offset"] = 179;
    $rsa_offsets_228["type_machine_rdth_len"] = 1;
    $rsa_offsets_228["type_dosimetrie_offset"] = 180;
    $rsa_offsets_228["type_dosimetrie_len"] = 1;
    $rsa_offsets_228["numero_innovation_offset"] = 181;
    $rsa_offsets_228["numero_innovation_len"] = 15;
    $rsa_offsets_228["nombre_ivg_anterieures_offset"] = 0;
    $rsa_offsets_228["nombre_ivg_anterieures_len"] = 0;
    $rsa_offsets_228["annee_ivg_precedente_offset"] = 0;
    $rsa_offsets_228["annee_ivg_precedente_len"] = 0;
    $rsa_offsets_228["nombre_naissances_vivantes_anterieures_offset"] = 0;
    $rsa_offsets_228["nombre_naissances_vivantes_anterieures_len"] = 0;
    $rsa_offsets_228["no_rum_dp_offset"] = 209;
    $rsa_offsets_228["no_rum_dp_len"] = 2;
    $rsa_offsets_228["diagnostic_principal_offset"] = 211;
    $rsa_offsets_228["diagnostic_principal_len"] = 6;
    $rsa_offsets_228["diagnostic_relie_offset"] = 217;
    $rsa_offsets_228["diagnostic_relie_len"] = 6;
    $rsa_offsets_228["nb_das_offset"] = 223;
    $rsa_offsets_228["nb_das_len"] = 6;

    $rss_offsets_229 = array();

    $rsa_offsets_229["finess_offset"] = 0;
    $rsa_offsets_229["finess_len"] = 9;
    $rsa_offsets_229["version_format_rsa_offset"] = 9;
    $rsa_offsets_229["version_format_rsa_len"] = 3;
    $rsa_offsets_229["no_rsa_offset"] = 12;
    $rsa_offsets_229["no_rsa_len"] = 10;
    $rsa_offsets_229["version_format_offset"] = 22;
    $rsa_offsets_229["version_format_len"] = 3;
    $rsa_offsets_229["numero_tarif_offset"] = 25;
    $rsa_offsets_229["numero_tarif_len"] = 3;
    $rsa_offsets_229["version_groupage_offset"] = 28;
    $rsa_offsets_229["version_groupage_len"] = 2;
    $rsa_offsets_229["ghm_offset"] = 30;
    $rsa_offsets_229["ghm_len"] = 6;
    $rsa_offsets_229["code_retour_groupage_offset"] = 36;
    $rsa_offsets_229["code_retour_groupage_len"] = 3;
    $rsa_offsets_229["version_groupage_genrsa_offset"] = 39;
    $rsa_offsets_229["version_groupage_genrsa_len"] = 2;
    $rsa_offsets_229["ghm_genrsa_offset"] = 41;
    $rsa_offsets_229["ghm_genrsa_len"] = 6;
    $rsa_offsets_229["code_retour_groupage_genrsa_offset"] = 47;
    $rsa_offsets_229["code_retour_groupage_genrsa_len"] = 3;
    $rsa_offsets_229["nombre_rum_offset"] = 50;
    $rsa_offsets_229["nombre_rum_len"] = 2;
    $rsa_offsets_229["age_annees_offset"] = 52;
    $rsa_offsets_229["age_annees_len"] = 3;
    $rsa_offsets_229["age_jours_offset"] = 55;
    $rsa_offsets_229["age_jours_len"] = 3;
    $rsa_offsets_229["sexe_offset"] = 58;
    $rsa_offsets_229["sexe_len"] = 1;
    $rsa_offsets_229["mode_entree_offset"] = 59;
    $rsa_offsets_229["mode_entree_len"] = 1;
    $rsa_offsets_229["provenance_offset"] = 60;
    $rsa_offsets_229["provenance_len"] = 1;
    $rsa_offsets_229["mois_sortie_offset"] = 61;
    $rsa_offsets_229["mois_sortie_len"] = 6;
    $rsa_offsets_229["mode_sortie_offset"] = 67;
    $rsa_offsets_229["mode_sortie_len"] = 1;
    $rsa_offsets_229["destination_offset"] = 68;
    $rsa_offsets_229["destination_len"] = 1;
    $rsa_offsets_229["type_sejour_offset"] = 69;
    $rsa_offsets_229["type_sejour_len"] = 1;
    $rsa_offsets_229["duree_sejour_offset"] = 70;
    $rsa_offsets_229["duree_sejour_len"] = 4;
    $rsa_offsets_229["code_geographique_offset"] = 74;
    $rsa_offsets_229["code_geographique_len"] = 5;
    $rsa_offsets_229["poids_entree_offset"] = 79;
    $rsa_offsets_229["poids_entree_len"] = 4;
    $rsa_offsets_229["age_gestationnel_offset"] = 83;
    $rsa_offsets_229["age_gestationnel_len"] = 2;
    $rsa_offsets_229["delai_dernieres_regles_offset"] = 85;
    $rsa_offsets_229["delai_dernieres_regles_len"] = 3;
    $rsa_offsets_229["nombre_seances_offset"] = 93;
    $rsa_offsets_229["nombre_seances_len"] = 2;
    $rsa_offsets_229["igs2_offset"] = 0;
    $rsa_offsets_229["igs2_len"] = 0;
    $rsa_offsets_229["ghs_genrsa_offset"] = 95;
    $rsa_offsets_229["ghs_genrsa_len"] = 4;
    $rsa_offsets_229["nombre_exh_offset"] = 99;
    $rsa_offsets_229["nombre_exh_len"] = 4;
    $rsa_offsets_229["type_exb_offset"] = 103;
    $rsa_offsets_229["type_exb_len"] = 1;
    $rsa_offsets_229["nb_exb_offset"] = 104;
    $rsa_offsets_229["nb_exb_len"] = 3;
    $rsa_offsets_229["top_adm_maison_naissance_offset"] = 107;
    $rsa_offsets_229["top_adm_maison_naissance_len"] = 1;
    $rsa_offsets_229["top_radiation_part_avastin_offset"] = 108;
    $rsa_offsets_229["top_radiation_part_avastin_len"] = 1;
    $rsa_offsets_229["top_radiation_partielle_alimta_offset"] = 109;
    $rsa_offsets_229["top_radiation_partielle_alimta_len"] = 1;
    $rsa_offsets_229["top_uhcd_offset"] = 110;
    $rsa_offsets_229["top_uhcd_len"] = 1;
    $rsa_offsets_229["top_ghs_minore_offset"] = 111;
    $rsa_offsets_229["top_ghs_minore_len"] = 1;
    $rsa_offsets_229["confirmation_codage_offset"] = 112;
    $rsa_offsets_229["confirmation_codage_len"] = 1;
    $rsa_offsets_229["nb_aut_pgv_offset"] = 113;
    $rsa_offsets_229["nb_aut_pgv_len"] = 1;
    $rsa_offsets_229["nb_sup_dialyse_1_offset"] = 114;
    $rsa_offsets_229["nb_sup_dialyse_1_len"] = 3;
    $rsa_offsets_229["nb_sup_dialyse_2_offset"] = 117;
    $rsa_offsets_229["nb_sup_dialyse_2_len"] = 3;
    $rsa_offsets_229["nb_sup_dialyse_3_offset"] = 120;
    $rsa_offsets_229["nb_sup_dialyse_3_len"] = 3;
    $rsa_offsets_229["nb_sup_dialyse_4_offset"] = 123;
    $rsa_offsets_229["nb_sup_dialyse_4_len"] = 3;
    $rsa_offsets_229["nb_sup_apherese_offset"] = 126;
    $rsa_offsets_229["nb_sup_apherese_len"] = 3;
    $rsa_offsets_229["nb_sup_rap_offset"] = 129;
    $rsa_offsets_229["nb_sup_rap_len"] = 3;
    $rsa_offsets_229["nb_sup_ant_offset"] = 132;
    $rsa_offsets_229["nb_sup_ant_len"] = 3;
    $rsa_offsets_229["nb_rdth_offset"] = 135;
    $rsa_offsets_229["nb_rdth_len"] = 1;
    $rsa_offsets_229["top_valve_aortique_offset"] = 136;
    $rsa_offsets_229["top_valve_aortique_len"] = 1;
    $rsa_offsets_229["type_generation_automarique_offset"] = 137;
    $rsa_offsets_229["type_generation_automarique_len"] = 1;
    $rsa_offsets_229["nb_sup_hyperbare_offset"] = 145;
    $rsa_offsets_229["nb_sup_hyperbare_len"] = 3;
    $rsa_offsets_229["type_prestation_prelevement_organe_offset"] = 153;
    $rsa_offsets_229["type_prestation_prelevement_organe_len"] = 1;
    $rsa_offsets_229["nb_sup_rea_offset"] = 154;
    $rsa_offsets_229["nb_sup_rea_len"] = 3;
    $rsa_offsets_229["nb_sup_si_offset"] = 157;
    $rsa_offsets_229["nb_sup_si_len"] = 3;
    $rsa_offsets_229["nb_sup_stf_offset"] = 160;
    $rsa_offsets_229["nb_sup_stf_len"] = 3;
    $rsa_offsets_229["nb_sup_usip_offset"] = 163;
    $rsa_offsets_229["nb_sup_usip_len"] = 3;
    $rsa_offsets_229["nb_sup_src_offset"] = 166;
    $rsa_offsets_229["nb_sup_src_len"] = 3;
    $rsa_offsets_229["nb_sup_nn1_offset"] = 169;
    $rsa_offsets_229["nb_sup_nn1_len"] = 3;
    $rsa_offsets_229["nb_sup_nn2_offset"] = 172;
    $rsa_offsets_229["nb_sup_nn2_len"] = 3;
    $rsa_offsets_229["nb_sup_nn3_offset"] = 175;
    $rsa_offsets_229["nb_sup_nn3_len"] = 3;
    $rsa_offsets_229["nb_sup_rep_offset"] = 178;
    $rsa_offsets_229["nb_sup_rep_len"] = 3;
    $rsa_offsets_229["passage_lit_sp_offset"] = 181;
    $rsa_offsets_229["passage_lit_sp_len"] = 1;
    $rsa_offsets_229["type_machine_rdth_offset"] = 182;
    $rsa_offsets_229["type_machine_rdth_len"] = 1;
    $rsa_offsets_229["type_dosimetrie_offset"] = 183;
    $rsa_offsets_229["type_dosimetrie_len"] = 1;
    $rsa_offsets_229["numero_innovation_offset"] = 184;
    $rsa_offsets_229["numero_innovation_len"] = 1;
    $rsa_offsets_229["nombre_ivg_anterieures_offset"] = 0;
    $rsa_offsets_229["nombre_ivg_anterieures_len"] = 0;
    $rsa_offsets_229["annee_ivg_precedente_offset"] = 0;
    $rsa_offsets_229["annee_ivg_precedente_len"] = 0;
    $rsa_offsets_229["nombre_naissances_vivantes_anterieures_offset"] = 0;
    $rsa_offsets_229["nombre_naissances_vivantes_anterieures_len"] = 0;
    $rsa_offsets_229["no_rum_dp_offset"] = 212;
    $rsa_offsets_229["no_rum_dp_len"] = 2;
    $rsa_offsets_228["diagnostic_principal_offset"] = 214;
    $rsa_offsets_228["diagnostic_principal_len"] = 6;
    $rsa_offsets_228["diagnostic_relie_offset"] = 220;
    $rsa_offsets_228["diagnostic_relie_len"] = 6;
    $rsa_offsets_228["nb_das_offset"] = 226;
    $rsa_offsets_228["nb_das_len"] = 6;
}



function new_rss($from_no_rss, $oid) {

    global $rss_array;

    $from_no_rss = trim($from_no_rss);
    $rss_array[$from_no_rss] = $oid;
    
}


/**
 * Permet de retrouver le rss_id correspondant à l'import grâce au no_rss
 * Crée la première fois un tableau de concordance entre rss et no_rss
 */
function get_rss($from_no_rss) {

    global $iCTI_connexion;
    global $rss_array;
    global $ok_rss_array;
    global $last_oid;
    global $last_no_rss;
    
    global $import_id;

    
    $from_no_rss = trim($from_no_rss);
    

    // On crée le tableau no_rss et oid une seuile fois
    if ($ok_rss_array !== TRUE || $from_no_rss == "*setarray") {
        $rss_array = array();
        $result = $iCTI_connexion->query("SELECT no_rss, oid FROM temp.p_rss WHERE import_id = $import_id ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $no_rss = trim($record["no_rss"]);
                $oid = $record["oid"];
                $rss_array[$no_rss] = $oid;
            }
        }
        $ok_rss_array = TRUE;
    }
    
    

    $oid = 0;
    if ($from_no_rss != "*setarray") {
        if ($from_no_rss == $last_no_rss) {
            return $last_oid;
        }
        if ($ok_rss_array === TRUE) {
            $oid = @$rss_array[$from_no_rss];
            if (get_num($oid) == 0) {
                $oid = 0;
            }
            
        }
    }
    
    $last_no_rss = $from_no_rss;
    $last_oid = $oid;
    
    return $oid;
    
}



function get_sejour_administratif_from_sejour($from_no_sejour_administratif) {

    global $iCTI_connexion;
    global $sejour_administratif_array;
    global $ok_sejour_administratif_array;
    global $last_oid;
    global $last_no_sejour_administratif;
    
    global $import_id;
    
    $from_no_sejour_administratif = trim($from_no_sejour_administratif);

    if ($ok_sejour_administratif_array !== TRUE || $from_no_sejour_administratif == "*setarray") {
        $sejour_administratif_array = array();
        $result = $iCTI_connexion->query("SELECT no_sejour_administratif, oid FROM pmsi.p_rss WHERE import_id = $import_id ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $no_sejour_administratif = trim($record["no_sejour_administratif"]);
                $oid = $record["oid"];
                $sejour_administratif_array[$no_sejour_administratif] = $oid;
            }
        }
        $ok_sejour_administratif_array = TRUE;
    }
    
    

    $oid = 0;
    if ($from_no_sejour_administratif != "*setarray") {
        if ($from_no_sejour_administratif == $last_no_sejour_administratif) {
            return $last_oid;
        }
        if ($ok_sejour_administratif_array === TRUE) {
            $oid = @$sejour_administratif_array[$from_no_sejour_administratif];
            if (get_num($oid) == 0) {
                $oid = 0;
            }
            
        }
    }
    
    $last_no_sejour_administratif = $from_no_sejour_administratif;
    $last_oid = $oid;
    
    return $oid;
    
}

function get_rss_um($from_rss_id) {

    global $iCTI_connexion;
    global $rss_um_array;
    global $ok_rss_um_array;
    global $last_um_id;
    global $last_rss_id_um;
    
    global $import_id;
    
    $from_rss_id = trim($from_rss_id);
    
    if ($ok_rss_um_array !== TRUE || $from_rss_id == "*setarray") {
        $rss_um_array = array();
        $result = $iCTI_connexion->query("SELECT oid, unite_medicale_principale_id FROM pmsi.p_rss WHERE import_id = $import_id ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $oid = trim($record["oid"]);
                $unite_medicale_principale_id = $record["unite_medicale_principale_id"];
                $rss_um_array[$oid] = $unite_medicale_principale_id;
            }
        }
        $ok_rss_um_array = TRUE;
    }
    
    

    $oid = 0;
    if ($from_rss_id != "*setarray") {
        if ($from_rss_id == $last_rss_id_um) {
            return $last_um_id;
        }
        if ($ok_rss_um_array === TRUE) {
            $oid = @$rss_um_array[$from_rss_id];
            if (get_num($oid) == 0) {
                $oid = 0;
            }
            
        }
    }
    
    $last_rss_id_um = $from_rss_id;
    $last_um_id = $oid;
    
    return $oid;
    


}


function get_unite_medicale($from_code) {

    global $iCTI_connexion;
    global $unites_medicales_array;
    global $ok_unites_medicales_array;
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    if ($ok_unites_medicales_array !== TRUE) {
        $unites_medicales_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_unites_medicales ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $unites_medicales_array[$code] = $oid;
            }
        }
        $ok_unites_medicales_array = TRUE;
    }
    

    $oid = 0;
    if ($ok_unites_medicales_array === TRUE) {
        $oid = @$unites_medicales_array[$from_code];
        if (get_num($oid) > 0) {

        }
        else {
            $sqlcmd = "INSERT INTO pmsi.t_unites_medicales( ";
            $sqlcmd = $sqlcmd . "code,  ";
            $sqlcmd = $sqlcmd . "texte,  ";
            $sqlcmd = $sqlcmd . "type_autorisation  ";
            $sqlcmd = $sqlcmd . ") ";
            $sqlcmd = $sqlcmd . "VALUES( ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "'$type_autorisation'  ";
            $sqlcmd = $sqlcmd . ") ";
            
            $toResult = execute_sql($sqlcmd, $nbE, $nbW );
            
            $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_unites_medicales WHERE code = '$from_code'");
            $ok = TRUE;
            while ($ok == TRUE) {
                $ok = FALSE;
                $record = pg_fetch_array($result);
                if ($record != FALSE) {
                    $ok = TRUE;
                    $code = trim($record["code"]);
                    $oid = $record["oid"];
                    $unites_medicales_array[$code] = $oid;
                }
            }
            
        }
    }
    
    return $oid;
    


}


function get_mode_entree($from_code) {

    global $iCTI_connexion;
    global $modes_entree_array;
    global $ok_modes_entree_array;
    
    $oid = 0;
    
    if ($from_code == "") {
        $oid = $from_code;
        return $oid;
    }
    if ($from_code == "0") {
        $oid = $from_code;
        return $oid;
    }
    
    if ($ok_modes_entree_array !== TRUE) {
        $modes_entree_array = array();
        $result = $iCTI_connexion->query("SELECT code, code as oid FROM pmsi.t_modes_entree ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $modes_entree_array[$code] = $oid;
            }
        }
        
        $ok_modes_entree_array = TRUE;
    }
    

    $oid = 0;
    if ($ok_modes_entree_array === TRUE) {
        $oid = @$modes_entree_array[$from_code];
        if (trim($oid) != '') {

        }
        else {
            $sqlcmd = "INSERT INTO pmsi.t_modes_entree( ";
            $sqlcmd = $sqlcmd . "code,  ";
            $sqlcmd = $sqlcmd . "texte  ";
            $sqlcmd = $sqlcmd . ") ";
            $sqlcmd = $sqlcmd . "VALUES( ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "'$from_code'  ";
            $sqlcmd = $sqlcmd . ") ";
            
            $toResult = execute_sql($sqlcmd, $nbE, $nbW );
            
            $result = $iCTI_connexion->query("SELECT code, code as oid FROM pmsi.t_modes_entree WHERE code = '$from_code'");
            $ok = TRUE;
            while ($ok == TRUE) {
                $ok = FALSE;
                $record = pg_fetch_array($result);
                if ($record != FALSE) {
                    $ok = TRUE;
                    $code = trim($record["code"]);
                    $oid = $record["oid"];
                    $modes_entree_array[$code] = $oid;
                }
            }
            
        }
    }
    
    
    return $oid;
    

}

function check_mode_entree($from_code, &$gravite, &$error, &$commentaire) {

    global $iCTI_connexion;
    global $modes_entree_array;
    global $ok_modes_entree_array;
    
    $error = "";
    $commentaire = "";
    $gravite = 0;
    
    if ($from_code == "") {
        return TRUE;
    }
    if ($from_code == "0") {
        return TRUE;
    }
    
    if ($ok_modes_entree_array !== TRUE) {
        $modes_entree_array = array();
        $result = $iCTI_connexion->query("SELECT code, code as oid FROM pmsi.t_modes_entree ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $modes_entree_array[$code] = $oid;
            }
        }
        
        $ok_modes_entree_array = TRUE;
    }
    

    if ($ok_modes_entree_array === TRUE) {
        $oid = @$modes_entree_array[$from_code];
        if (get_num($oid) == 0) {
            $gravite = 0;
            $error = "Code $from_code inexistant";
            $commentaire = "Ce code sera créé";
            return FALSE;
        }
        
    }
    
    
    return TRUE;
    


}


function get_mode_sortie($from_code) {

    global $iCTI_connexion;
    global $modes_sortie_array;
    global $ok_modes_sortie_array;
    
    $oid = 0;
    
    if ($from_code == "") {
        $oid = $from_code;
        return $oid;
    }
    if ($from_code == "0") {
        $oid = $from_code;
        return $oid;
    }
    
    if ($ok_modes_sortie_array !== TRUE) {
        $modes_sortie_array = array();
        $result = $iCTI_connexion->query("SELECT code, code as oid FROM pmsi.t_modes_sortie ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $modes_sortie_array[$code] = $oid;
            }
        }
        
        $ok_modes_sortie_array = TRUE;
    }
    

    $oid = 0;
    if ($ok_modes_sortie_array === TRUE) {
        $oid = @$modes_sortie_array[$from_code];
        if (get_num($oid) > 0) {

        }
        else {
            $sqlcmd = "INSERT INTO pmsi.t_modes_sortie( ";
            $sqlcmd = $sqlcmd . "code,  ";
            $sqlcmd = $sqlcmd . "texte  ";
            $sqlcmd = $sqlcmd . ") ";
            $sqlcmd = $sqlcmd . "VALUES( ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "'$from_code'  ";
            $sqlcmd = $sqlcmd . ") ";
            
            $toResult = execute_sql($sqlcmd, $nbE, $nbW );
            
            $result = $iCTI_connexion->query("SELECT code, code as oid FROM pmsi.t_modes_sortie WHERE code = '$from_code'");
            $ok = TRUE;
            while ($ok == TRUE) {
                $ok = FALSE;
                $record = pg_fetch_array($result);
                if ($record != FALSE) {
                    $ok = TRUE;
                    $code = trim($record["code"]);
                    $oid = $record["oid"];
                    $modes_sortie_array[$code] = $oid;
                }
            }
            
        }
    }
    
    
    return $oid;
    

}


function check_mode_sortie($from_code, &$gravite, &$error, &$commentaire) {

    global $iCTI_connexion;
    global $modes_sortie_array;
    global $ok_modes_sortie_array;
    
    $error = "";
    $commentaire = "";
    $gravite = 0;
    
    if ($from_code == "") {
        return TRUE;
    }
    if ($from_code == "0") {
        return TRUE;
    }
    
    if ($ok_modes_sortie_array !== TRUE) {
        $modes_sortie_array = array();
        $result = $iCTI_connexion->query("SELECT code, code as oid FROM pmsi.t_modes_sortie ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $modes_sortie_array[$code] = $oid;
            }
        }
        
        $ok_modes_sortie_array = TRUE;
    }
    

    if ($ok_modes_sortie_array === TRUE) {
        $oid = @$modes_sortie_array[$from_code];
        if (get_num($oid) == 0) {
            $gravite = 0;
            $error = "Code $from_code inexistant";
            $commentaire = "Ce code sera créé";
            return FALSE;
        }
        
    }
    
    
    return TRUE;
    


}

function get_provenance($from_code) {

    global $iCTI_connexion;
    global $provenances_entree_array;
    global $ok_provenances_entree_array;
    
    $oid = "0";
    
    if ($from_code == "") {
        $oid = $from_code;
        return $oid;
    }
    
    if ($ok_provenances_entree_array !== TRUE) {
        $provenances_entree_array = array();
        $result = $iCTI_connexion->query("SELECT code, code as oid FROM pmsi.t_provenances_entree ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $provenances_entree_array[$code] = $oid;
            }
        }
        
        $ok_provenances_entree_array = TRUE;
    }
    

    $oid = "";
    if ($ok_provenances_entree_array === TRUE) {
        $oid = @$provenances_entree_array[$from_code];
        if ($oid != "") {

        }
        else {
            $sqlcmd = "INSERT INTO pmsi.t_provenances_entree( ";
            $sqlcmd = $sqlcmd . "code,  ";
            $sqlcmd = $sqlcmd . "texte  ";
            $sqlcmd = $sqlcmd . ") ";
            $sqlcmd = $sqlcmd . "VALUES( ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "'$from_code'  ";
            $sqlcmd = $sqlcmd . ") ";
            
            $toResult = execute_sql($sqlcmd, $nbE, $nbW );
            
            $result = $iCTI_connexion->query("SELECT code, code as oid FROM pmsi.t_provenances_entree WHERE code = '$from_code'");
            $ok = TRUE;
            while ($ok == TRUE) {
                $ok = FALSE;
                $record = pg_fetch_array($result);
                if ($record != FALSE) {
                    $ok = TRUE;
                    $code = trim($record["code"]);
                    $oid = $record["oid"];
                    $provenances_entree_array[$code] = $oid;
                }
            }
            
        }
    }
    
    
    return $oid;
    

}

function check_provenance($from_code, &$gravite, &$error, &$commentaire) {

    global $iCTI_connexion;
    global $provenances_array;
    global $ok_provenances_array;
    
    $error = "";
    $commentaire = "";
    $gravite = 0;
    
    if ($from_code == "") {
        return TRUE;
    }
    
    if ($ok_provenances_array !== TRUE) {
        $provenances_array = array();
        $result = $iCTI_connexion->query("SELECT code, code as oid FROM pmsi.t_provenances_entree ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $provenances_array[$code] = $oid;
            }
        }
        
        $ok_provenances_array = TRUE;
    }
    
    if ($ok_provenances_array === TRUE) {
        $oid = "";
        $oid = @$provenances_array[$from_code];
        if ($oid == "") {
            $gravite = 0;
            $error = "Code $from_code inexistant";
            $commentaire = "Ce code sera créé";
            return FALSE;
        }
        
    }
    
    
    return TRUE;
    


}


function check_passage_urgences($from_code, &$gravite, &$error, &$commentaire) {

    global $iCTI_connexion;
    global $passage_urgences_array;
    global $ok_passage_urgences_array;

    $error       = "";
    $commentaire = "";
    $gravite     = 0;


    if ($ok_passage_urgences_array !== TRUE) {
        $passage_urgences_array   = array();
        $sqlcmd                      = "SELECT code, oid FROM pmsi.t_passage_urgences ";
        $result = $iCTI_connexion->query($sqlcmd);                  
        $ok                          = TRUE;
        while ($ok == TRUE) {
            $ok      = FALSE;
            $record  = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok                                  = TRUE;
                $code                                = trim($record["code"]);
                $oid                                 = $record["oid"];
                $passage_urgences_array[$code]    = $oid;
            }
        }

        $ok_passage_urgences_array = TRUE;
    }


    if ($ok_passage_urgences_array === TRUE) {
        $oid = @$passage_urgences_array[$from_code];
        if (get_num($oid) == 0) {
            $gravite     = 0;
            $error       = "Code $from_code inexistant";
            $commentaire = "Ce code sera créé";
            return FALSE;
        }
    }


    return TRUE;
}

function get_destination($from_code) {

    global $iCTI_connexion;
    global $destinations_sortie_array;
    global $ok_destinations_sortie_array;
    
    $oid = "0";
    
    if ($from_code == "") {
        $oid = $from_code;
        return $oid;
    }
    
    if ($ok_destinations_sortie_array !== TRUE) {
        $destinations_sortie_array = array();
        $result = $iCTI_connexion->query("SELECT code, code as oid FROM pmsi.t_destinations_sortie ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $destinations_sortie_array[$code] = $oid;
            }
        }
        
        $ok_destinations_sortie_array = TRUE;
    }
    

    $oid = "";
    if ($ok_destinations_sortie_array === TRUE) {
        $oid = @$destinations_sortie_array[$from_code];
        if ($oid != "") {

        }
        else {
            $sqlcmd = "INSERT INTO pmsi.t_destinations_sortie( ";
            $sqlcmd = $sqlcmd . "code,  ";
            $sqlcmd = $sqlcmd . "texte  ";
            $sqlcmd = $sqlcmd . ") ";
            $sqlcmd = $sqlcmd . "VALUES( ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "'$from_code'  ";
            $sqlcmd = $sqlcmd . ") ";
            
            $toResult = execute_sql($sqlcmd, $nbE, $nbW );
            
            $result = $iCTI_connexion->query("SELECT code, code as oid FROM pmsi.t_destinations_sortie WHERE code = '$from_code'");
            $ok = TRUE;
            while ($ok == TRUE) {
                $ok = FALSE;
                $record = pg_fetch_array($result);
                if ($record != FALSE) {
                    $ok = TRUE;
                    $code = trim($record["code"]);
                    $oid = $record["oid"];
                    $destinations_sortie_array[$code] = $oid;
                }
            }
            
        }
    }
    
    
    return $oid;
    

}

function check_destination($from_code, &$gravite, &$error, &$commentaire) {

    global $iCTI_connexion;
    global $destinations_array;
    global $ok_destinations_array;
    
    $error = "";
    $commentaire = "";
    $gravite = 0;
    
    if ($from_code == "") {
        return TRUE;
    }
    
    if ($ok_destinations_array !== TRUE) {
        $destinations_array = array();
        $result = $iCTI_connexion->query("SELECT code, code as oid FROM pmsi.t_destinations_sortie ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $destinations_array[$code] = $oid;
            }
        }
        
        $ok_destinations_array = TRUE;
    }
    

    if ($ok_destinations_array === TRUE) {
        $oid = "";
        $oid = @$destinations_array[$from_code];
        if ($oid == "") {
            $gravite = 0;
            $error = "Code $from_code inexistant";
            $commentaire = "Ce code sera créé";
            return FALSE;
        }
        
    }
    
    
    return TRUE;
    


}

function get_diagnostic($from_code) {

    global $iCTI_connexion;
    global $diagnostics_array;
    global $ok_diagnostics_array;
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    if ($ok_diagnostics_array !== TRUE) {
        $diagnostics_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_diagnostics ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $diagnostics_array[$code] = $oid;
            }
        }
        
        $ok_diagnostics_array = TRUE;
    }
    

    $oid = 0;
    if ($ok_diagnostics_array === TRUE) {
        $oid = @$diagnostics_array[$from_code];
        if (get_num($oid) > 0) {

        }
        else {
            $sqlcmd = "INSERT INTO pmsi.t_diagnostics( ";
            $sqlcmd = $sqlcmd . "code,  ";
            $sqlcmd = $sqlcmd . "texte  ";
            $sqlcmd = $sqlcmd . ") ";
            $sqlcmd = $sqlcmd . "VALUES( ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "'$from_code'  ";
            $sqlcmd = $sqlcmd . ") ";
            
            $toResult = execute_sql($sqlcmd, $nbE, $nbW );
            
            $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_diagnostics WHERE code = '$from_code'");
            $ok = TRUE;
            while ($ok == TRUE) {
                $ok = FALSE;
                $record = pg_fetch_array($result);
                if ($record != FALSE) {
                    $ok = TRUE;
                    $code = trim($record["code"]);
                    $oid = $record["oid"];
                    $diagnostics_array[$code] = $oid;
                }
            }
            
        }
    }
    
    
    return $oid;
    


}

function get_code_retour($from_code) {

    global $iCTI_connexion;
    global $codes_retour_array;
    global $ok_code_retour_array;
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    if ($ok_code_retour_array !== TRUE) {
        $codes_retour_array = array();
        $result = $iCTI_connexion->query("SELECT type || code as code, oid FROM pmsi.t_codes_retour_groupeur ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $codes_retour_array[$code] = $oid;
            }
        }
        
        $ok_code_retour_array = TRUE;
    }
    

    $oid = 0;
    if ($ok_code_retour_array === TRUE) {
        $oid = @$codes_retour_array[$from_code];
        if (get_num($oid) > 0) {

        }
        else {
            $type = substr($from_code, 0, 1);
            $code = substr($from_code, 1);
            $sqlcmd = "INSERT INTO pmsi.t_codes_retour_groupeur( type, code, texte ) VALUES( '$type', '$code', '$from_code' ) ";
            
            $toResult = execute_sql($sqlcmd, $nbE, $nbW );
            
            $result = $iCTI_connexion->query("SELECT type || code as code, oid FROM pmsi.t_codes_retour_groupeur WHERE type || code = '$from_code'");
            $ok = TRUE;
            while ($ok == TRUE) {
                $ok = FALSE;
                $record = pg_fetch_array($result);
                if ($record != FALSE) {
                    $ok = TRUE;
                    $code = trim($record["code"]);
                    $oid = $record["oid"];
                    $codes_retour_array[$code] = $oid;
                }
            }
            
        }
    }
    return $oid;
}

/*
*Retourne  le code de modificateur 
*/
function get_modificateur($from_code) {

    global $iCTI_connexion;
    global $modificateurs_array;
    global $ok_modificateurs_array;
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    if ($ok_modificateurs_array !== TRUE) {
        $modificateurs_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_modificateurs_ccam ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $modificateurs_array[$code] = $oid;
            }
        }
        
        $ok_modificateurs_array = TRUE;
    }

    $oid = 0;
    if ($ok_modificateurs_array === TRUE) {
        $oid = @$modificateurs_array[$from_code];
        $lenth = strlen ($from_code );
        if (get_num($oid) > 0 ) {

        }
        else {
            $sqlcmd = "INSERT INTO pmsi.t_modificateurs_ccam( ";
            $sqlcmd = $sqlcmd . "code,  ";
            $sqlcmd = $sqlcmd . "texte,  ";
            $sqlcmd = $sqlcmd . "texte_court  ";
            $sqlcmd = $sqlcmd . ") ";
            $sqlcmd = $sqlcmd . "VALUES( ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "'$from_code'  ";
            $sqlcmd = $sqlcmd . ") ";
            
            $toResult = execute_sql($sqlcmd, $nbE, $nbW );
            
            $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_modificateurs_ccam WHERE code = '$from_code'");
            $ok = TRUE;
            while ($ok == TRUE) {
                $ok = FALSE;
                $record = pg_fetch_array($result);
                if ($record != FALSE) {
                    $ok = TRUE;
                    $code = trim($record["code"]);
                    $oid = $record["oid"];
                    $modificateurs_array[$code] = $oid;
                }
            }
            
        }
    }
    
    return $oid;

}

function check_modificateur($from_code, &$gravite, &$error, &$commentaire) {

    global $iCTI_connexion;
    global $modificateurs_array;
    global $ok_modificateurs_array ;
    
    $error = "";
    $commentaire = "";
    $gravite = 0;
    
    if (strlen($from_code) >1) {
        $gravite = 4;
        $error = "Code $from_code incorrect (taille du modificateur incorrecte)";
        return FALSE;
    }

    if ($ok_modificateurs_array !== TRUE) {
        $modificateurs_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_modificateurs_ccam ");

        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $modificateurs_array[$code] = $oid;
            }
        }
        
        $ok_modificateurs_array = TRUE;
    }
    
    
    if ($ok_modificateurs_array === TRUE  ) {
        $oid = @$modificateurs_array[$from_code];
            if (get_num($oid) == 0 && $from_code != "") {
                $res = get_modificateur($from_code);// appel de la fonction get_modificateur avec le modificateur d'indice i 
                $modificateurs_array[$from_code] = 99999999;
                $gravite = 1 ; 
                $error = "Code $from_code inexistant";
                $commentaire = "Ce code sera créé";
                return FALSE;
            }   
    }
    return TRUE;
    
}


/*
 * Retourne un tableau contenant les codes des modes d'hospitalisation
 */
function get_modes_hospitalisation() {

    global $iCTI_connexion;
    
    $modes_hospitalisation = array();
    $result = $iCTI_connexion->query(" SELECT code FROM base.t_modes_hospitalisation ");
    $ok = TRUE;
    while ($ok == TRUE) {
        $ok = FALSE;
        $record = pg_fetch_array($result);
        if ($record != FALSE) {
            $ok = TRUE;
            $modes_hospitalisation[] = trim($record["code"]);
        }
    }
    return $modes_hospitalisation;
}

/*
 * Retourne un tableau contenant les unités médicales
 */
function get_unites_medicales() {

    global $iCTI_connexion;
    
    $unites_medicales = array();
    $result = $iCTI_connexion->query(" SELECT code, type_autorisation, nb_lits, date_effet_autorisation, mode_hospitalisation FROM pmsi.t_unites_medicales ");
    $ok = TRUE;
    while ($ok == TRUE) {
        $ok = FALSE;
        $record = pg_fetch_array($result);
        if ($record != FALSE) {
            $ok = TRUE;
            $unite_medicale = array();
            $unite_medicale['type_autorisation'] = trim($record["type_autorisation"]);
            $unite_medicale['nb_lits'] = trim($record["nb_lits"]) + 0;
            $unite_medicale['date_effet_autorisation'] = trim($record["date_effet_autorisation"]);
            $unite_medicale['mode_hospitalisation'] = trim($record["mode_hospitalisation"]);
            $unites_medicales[trim($record["code"])] = $unite_medicale;
        }
    }
    return $unites_medicales;
}

/*
 * Retourne un tableau contenant les types d'autorisation d'unités médicales
 */
function get_types_autorisation() {

    global $iCTI_connexion;
    
    $types_autorisation = array();
    $result = $iCTI_connexion->query(" SELECT code FROM pmsi.t_types_autorisations ORDER BY 1");
    $ok = TRUE;
    while ($ok == TRUE) {
        $ok = FALSE;
        $record = pg_fetch_array($result);
        if ($record != FALSE) {
            $ok = TRUE;
            $types_autorisation[] = $record["code"];
        }
    }
    return $types_autorisation;
}


/**
 *  Donne l'oid d'un grand régime d'assurance dont le code est passé en paramètre. Si le code n'existe pas, il est ajouté en base
 */
function get_regime($from_code) {

    global $iCTI_connexion;
    global $regime_array;
    global $ok_regime_array;
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    if ($ok_regime_array !== TRUE) {
        $regime_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM base.t_grands_regimes");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $regime_array[$code] = $oid;
            }
        }
        $ok_regime_array = TRUE;
    }

    $oid = 0;
    if ($ok_regime_array === TRUE) {
        if (!array_key_exists($from_code, $regime_array)) {
            $sqlcmd = "INSERT INTO base.t_grands_regimes( code, texte, code_original ) VALUES( '$from_code', '$from_code', '$from_code' ) ";
            
            $toResult = execute_sql($sqlcmd, $nbE, $nbW );
            
            $result = $iCTI_connexion->query("SELECT code, oid FROM base.t_grands_regimes WHERE code = '$from_code'");
            $ok = TRUE;
            while ($ok == TRUE) {
                $ok = FALSE;
                $record = pg_fetch_array($result);
                if ($record != FALSE) {
                    $ok = TRUE;
                    $code = trim($record["code"]);
                    $oid = $record["oid"];
                    $regime_array[$code] = $oid;
                }
            }
        }
        else {
            $oid = $regime_array[$from_code];
        }
    }
    return $oid;
}

/**
 *  Donne l'oid d'un justificatif d'exonération du Ticket Modérateur dont le code est passé en paramètre. Si le code n'existe pas, il est ajouté en base
 */
function get_exoneration_tm($from_code) {

    global $iCTI_connexion;
    global $exoneration_tm_array;
    global $ok_exoneration_tm_array;
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    if ($ok_exoneration_tm_array !== TRUE) {
        $exoneration_tm_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM base.t_exoneration_tm");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $exoneration_tm_array[$code] = $oid;
            }
        }
        $ok_exoneration_tm_array = TRUE;
    }

    $oid = 0;
    if ($ok_exoneration_tm_array === TRUE) {
        if (!array_key_exists($from_code, $exoneration_tm_array)) {
            $sqlcmd = "INSERT INTO base.t_exoneration_tm( code, texte ) VALUES( '$from_code', '$from_code' ) ";
            
            $toResult = execute_sql($sqlcmd, $nbE, $nbW );
            
            $result = $iCTI_connexion->query("SELECT code, oid FROM base.t_exoneration_tm WHERE code = '$from_code'");
            $ok = TRUE;
            while ($ok == TRUE) {
                $ok = FALSE;
                $record = pg_fetch_array($result);
                if ($record != FALSE) {
                    $ok = TRUE;
                    $code = trim($record["code"]);
                    $oid = $record["oid"];
                    $exoneration_tm_array[$code] = $oid;
                }
            }
        }
        else {
            $oid = $exoneration_tm_array[$from_code];
        }
    }
    return $oid;
}

/**
 *  Donne l'oid de la facturation des 18 euros pour une facture dont le code (de la facturation 18 euros) est passé en paramètre. Si le code n'existe pas, il est ajouté en base
 */
function get_facturation_18euros($from_code) {

    global $iCTI_connexion;
    global $facturation_18euros_array;
    global $ok_facturation_18euros_array;
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    if ($ok_facturation_18euros_array !== TRUE) {
        $facturation_18euros_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM base.t_facturation_18euros");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $facturation_18euros_array[$code] = $oid;
            }
        }
        $ok_facturation_18euros_array = TRUE;
    }

    $oid = 0;
    if ($ok_facturation_18euros_array === TRUE) {
        if (!array_key_exists($from_code, $facturation_18euros_array)) {
            $sqlcmd = "INSERT INTO base.t_facturation_18euros( code, texte ) VALUES( '$from_code', '$from_code' ) ";
            
            $toResult = execute_sql($sqlcmd, $nbE, $nbW );
            
            $result = $iCTI_connexion->query("SELECT code, oid FROM base.t_facturation_18euros WHERE code = '$from_code'");
            $ok = TRUE;
            while ($ok == TRUE) {
                $ok = FALSE;
                $record = pg_fetch_array($result);
                if ($record != FALSE) {
                    $ok = TRUE;
                    $code = trim($record["code"]);
                    $oid = $record["oid"];
                    $facturation_18euros_array[$code] = $oid;
                }
            }
        }
        else {
            $oid = $facturation_18euros_array[$from_code];
        }
    }
    return $oid;
}

/**
 *  Donne l'oid d'une nature de prise en charge dont le code est passé en paramètre. Si le code n'existe pas, il est ajouté en base
 */
function get_nature_pec($from_code) {

    global $iCTI_connexion;
    global $nature_pec_array;
    global $ok_nature_pec_array;
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    if ($ok_nature_pec_array !== TRUE) {
        $nature_pec_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM base.t_nature_assurance");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $nature_pec_array[$code] = $oid;
            }
        }
        $ok_nature_pec_array = TRUE;
    }

    $oid = 0;
    if ($ok_nature_pec_array === TRUE) {
        if (!array_key_exists($from_code, $nature_pec_array)) {
            $sqlcmd = "INSERT INTO base.t_nature_assurance( code, texte ) VALUES( '$from_code', '$from_code' ) ";
            
            $toResult = execute_sql($sqlcmd, $nbE, $nbW );
            
            $result = $iCTI_connexion->query("SELECT code, oid FROM base.t_nature_assurance WHERE code = '$from_code'");
            $ok = TRUE;
            while ($ok == TRUE) {
                $ok = FALSE;
                $record = pg_fetch_array($result);
                if ($record != FALSE) {
                    $ok = TRUE;
                    $code = trim($record["code"]);
                    $oid = $record["oid"];
                    $nature_pec_array[$code] = $oid;
                }
            }
        }
        else {
            $oid = $nature_pec_array[$from_code];
        }
    }
    return $oid;
}

function get_pec($from_code) {

    global $iCTI_connexion;
    global $pec_array;
    global $ok_pec_array;
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    if ($ok_pec_array !== TRUE) {
        $pec_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM base.t_pec");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $pec_array[$code] = $oid;
            }
        }
        $ok_pec_array = TRUE;
    }

    $oid = 0;
    if ($ok_pec_array === TRUE) {
        if (!array_key_exists($from_code, $pec_array)) {
            $sqlcmd = "INSERT INTO base.t_pec( code, texte ) VALUES( '$from_code', '$from_code' ) ";
            
            $toResult = execute_sql($sqlcmd, $nbE, $nbW );
            
            $result = $iCTI_connexion->query("SELECT code, oid FROM base.t_pec WHERE code = '$from_code'");
            $ok = TRUE;
            while ($ok == TRUE) {
                $ok = FALSE;
                $record = pg_fetch_array($result);
                if ($record != FALSE) {
                    $ok = TRUE;
                    $code = trim($record["code"]);
                    $oid = $record["oid"];
                    $pec_array[$code] = $oid;
                }
            }
        }
        else {
            $oid = $pec_array[$from_code];
        }
    }
    return $oid;
}

function get_pec_fj($from_code) {

    global $iCTI_connexion;
    global $pec_fj_array;
    global $ok_pec_fj_array;
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    if ($ok_pec_fj_array !== TRUE) {
        $pec_fj_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM base.t_pec_fj");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $pec_fj_array[$code] = $oid;
            }
        }
        $ok_pec_fj_array = TRUE;
    }

    $oid = 0;
    if ($ok_pec_fj_array === TRUE) {
        if (!array_key_exists($from_code, $pec_fj_array)) {
            $sqlcmd = "INSERT INTO base.t_pec_fj( code, texte ) VALUES( '$from_code', '$from_code' ) ";
            
            $toResult = execute_sql($sqlcmd, $nbE, $nbW );
            
            $result = $iCTI_connexion->query("SELECT code, oid FROM base.t_pec_fj WHERE code = '$from_code'");
            $ok = TRUE;
            while ($ok == TRUE) {
                $ok = FALSE;
                $record = pg_fetch_array($result);
                if ($record != FALSE) {
                    $ok = TRUE;
                    $code = trim($record["code"]);
                    $oid = $record["oid"];
                    $pec_fj_array[$code] = $oid;
                }
            }
        }
        else {
            $oid = $pec_fj_array[$from_code];
        }
    }
    return $oid;
}

function get_type_uf_consultation($from_code) {

    global $iCTI_connexion;
    global $type_uf_consultation_array;
    global $ok_type_uf_consultation_array;
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    if ($ok_type_uf_consultation_array !== TRUE) {
        $type_uf_consultation_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_type_uf_consultation");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $type_uf_consultation_array[$code] = $oid;
            }
        }
        $ok_type_uf_consultation_array = TRUE;
    }

    $oid = 0;
    if ($ok_type_uf_consultation_array === TRUE) {
        if (!array_key_exists($from_code, $type_uf_consultation_array)) {
            $sqlcmd = "INSERT INTO pmsi.t_type_uf_consultation( code, texte ) VALUES( '$from_code', '$from_code' ) ";
            
            $toResult = execute_sql($sqlcmd, $nbE, $nbW );
            
            $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_type_uf_consultation WHERE code = '$from_code'");
            $ok = TRUE;
            while ($ok == TRUE) {
                $ok = FALSE;
                $record = pg_fetch_array($result);
                if ($record != FALSE) {
                    $ok = TRUE;
                    $code = trim($record["code"]);
                    $oid = $record["oid"];
                    $type_uf_consultation_array[$code] = $oid;
                }
            }
        }
        else {
            $oid = $type_uf_consultation_array[$from_code];
        }
    }
    return $oid;
}

function get_type_ucd($from_code) {
    
    global $iCTI_connexion;
    global $type_ucd_array;
    global $ok_type_ucd_array;
    
    // transforme le tpe de prestation fichcomp en code de t_type_ucd
    switch ($from_code) {
        case "09" : 
            $from_code = "ATU";
            break;
        case "10" :
            $from_code = "THROMBO";
            break;
        default :
            $from_code = "SUS";
            break;
    }
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    if ($ok_type_ucd_array !== TRUE) {
        $type_ucd_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_type_ucd");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $type_ucd_array[$code] = $oid;
            }
        }
        $ok_type_ucd_array = TRUE;
    }
    
    $oid = 0;
    if ($ok_type_ucd_array === TRUE && array_key_exists($from_code, $type_ucd_array)) {
            $oid = $type_ucd_array[$from_code];
    }
    return $oid;
}

function get_conversion_hp_hc($from_code) {
    
    global $iCTI_connexion;
    global $conversion_array;
    global $ok_conversion_array;
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    if ($ok_conversion_array !== TRUE) {
        $conversion_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_conversion_hp_hc");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $conversion_array[$code] = $oid;
            }
        }
        $ok_conversion_array = TRUE;
    }
    
    $oid = 0;
    if ($ok_conversion_array === TRUE && array_key_exists($from_code, $conversion_array)) {
        $oid = $conversion_array[$from_code];
    }
    return $oid;
}

function get_raac($from_code) {
    
    global $iCTI_connexion;
    global $raac_array;
    global $ok_raac_array;
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    if ($ok_raac_array !== TRUE) {
        $raac_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_raac");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $raac_array[$code] = $oid;
            }
        }
        $ok_raac_array = TRUE;
    }
    
    $oid = 0;
    if ($ok_raac_array === TRUE && array_key_exists($from_code, $raac_array)) {
        $oid = $raac_array[$from_code];
    }
    return $oid;
}

function get_np($from_code) {
    
    global $iCTI_connexion;
    global $np_aray;
    global $ok_np_aray;
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    if ($ok_np_aray !== TRUE) {
        $np_aray = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_np");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $np_aray[$code] = $oid;
            }
        }
        $ok_np_aray = TRUE;
    }
    
    $oid = 0;
    if ($ok_np_aray === TRUE && array_key_exists($from_code, $np_aray)) {
        $oid = $np_aray[$from_code];
    }
    return $oid;
}

function get_rescrit_tarif($from_code) {
    
    global $iCTI_connexion;
    global $rescrit_tarif_array;
    global $ok_rescrit_tarif_array;
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    if ($ok_rescrit_tarif_array !== TRUE) {
        $rescrit_tarif_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_rescrit_tarif");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $rescrit_tarif_array[$code] = $oid;
            }
        }
        $ok_rescrit_tarif_array = TRUE;
    }
    
    $oid = 0;
    if ($ok_rescrit_tarif_array === TRUE && array_key_exists($from_code, $rescrit_tarif_array)) {
        $oid = $rescrit_tarif_array[$from_code];
    }
    return $oid;
}

function get_adm_prod_reshospi($from_code) {
    
    global $iCTI_connexion;
    global $adm_prod_reshospi_array;
    global $ok_adm_prod_reshospi_array;
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    if ($ok_adm_prod_reshospi_array !== TRUE) {
        $adm_prod_reshospi_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_adm_prod_reshospi");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $adm_prod_reshospi_array[$code] = $oid;
            }
        }
        $ok_adm_prod_reshospi_array = TRUE;
    }
    
    $oid = 0;
    if ($ok_adm_prod_reshospi_array === TRUE && array_key_exists($from_code, $adm_prod_reshospi_array)) {
        $oid = $adm_prod_reshospi_array[$from_code];
    }
    return $oid;
}

function get_contexte_pat($from_code) {
    
    global $iCTI_connexion;
    global $contexte_pat_array;
    global $ok_contexte_pat_array;
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    if ($ok_contexte_pat_array !== TRUE) {
        $contexte_pat_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_contexte_pat");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $contexte_pat_array[$code] = $oid;
            }
        }
        $ok_contexte_pat_array = TRUE;
    }
    
    $oid = 0;
    if ($ok_contexte_pat_array === TRUE && array_key_exists($from_code, $contexte_pat_array)) {
        $oid = $contexte_pat_array[$from_code];
    }
    return $oid;
}

function get_nb_interventions($from_code) {
    
    global $iCTI_connexion;
    global $nb_interventions_array;
    global $ok_nb_interventions_array;
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    if ($ok_nb_interventions_array !== TRUE) {
        $nb_interventions_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_nb_interventions");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $nb_interventions_array[$code] = $oid;
            }
        }
        $ok_nb_interventions_array = TRUE;
    }
    
    $oid = 0;
    if ($ok_nb_interventions_array === TRUE && array_key_exists($from_code, $nb_interventions_array)) {
        $oid = $nb_interventions_array[$from_code];
    }
    return $oid;
}

function get_type_contrat_oc($from_code) {

    global $iCTI_connexion;
    global $type_contrat_oc_array;
    global $ok_type_contrat_oc_array;
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    if ($ok_type_contrat_oc_array !== TRUE) {
        $type_contrat_oc_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM base.t_type_contrat_oc");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $type_contrat_oc_array[$code] = $oid;
            }
        }
        $ok_type_contrat_oc_array = TRUE;
    }

    $oid = 0;
    if ($ok_type_contrat_oc_array === TRUE) {
        if (!array_key_exists($from_code, $type_contrat_oc_array)) {
            $sqlcmd = "INSERT INTO base.t_type_contrat_oc( code, texte ) VALUES( '$from_code', '$from_code' ) ";
            
            $toResult = execute_sql($sqlcmd, $nbE, $nbW );
            
            $result = $iCTI_connexion->query("SELECT code, oid FROM base.t_type_contrat_oc WHERE code = '$from_code'");
            $ok = TRUE;
            while ($ok == TRUE) {
                $ok = FALSE;
                $record = pg_fetch_array($result);
                if ($record != FALSE) {
                    $ok = TRUE;
                    $code = trim($record["code"]);
                    $oid = $record["oid"];
                    $type_contrat_oc_array[$code] = $oid;
                }
            }
        }
        else {
            $oid = $type_contrat_oc_array[$from_code];
        }
    }
    return $oid;
}

function get_motif_non_facturation($from_code) {

    global $iCTI_connexion;
    global $motif_non_facturation_array;
    global $ok_motif_non_facturation_array;
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    if ($ok_motif_non_facturation_array !== TRUE) {
        $motif_non_facturation_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM base.t_motif_non_facturation");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $motif_non_facturation_array[$code] = $oid;
            }
        }
        $ok_motif_non_facturation_array = TRUE;
    }

    $oid = 0;
    if ($ok_motif_non_facturation_array === TRUE) {
        if (!array_key_exists($from_code, $motif_non_facturation_array)) {
            $sqlcmd = "INSERT INTO base.t_motif_non_facturation( code, texte ) VALUES( '$from_code', '$from_code' ) ";
            
            $toResult = execute_sql($sqlcmd, $nbE, $nbW );
            
            $result = $iCTI_connexion->query("SELECT code, oid FROM base.t_motif_non_facturation WHERE code = '$from_code'");
            $ok = TRUE;
            while ($ok == TRUE) {
                $ok = FALSE;
                $record = pg_fetch_array($result);
                if ($record != FALSE) {
                    $ok = TRUE;
                    $code = trim($record["code"]);
                    $oid = $record["oid"];
                    $motif_non_facturation_array[$code] = $oid;
                }
            }
        }
        else {
            $oid = $motif_non_facturation_array[$from_code];
        }
    }
    return $oid;
}

function check_diagnostic($from_code, &$gravite, &$error, &$commentaire) {

    global $iCTI_connexion;
    global $diagnostics_array;
    global $ok_diagnostics_array;
    
    $error = "";
    $commentaire = "";
    $gravite = 0;
    
    if (substr($from_code , 0, 1) < 'A' || substr($from_code , 0, 1) > 'Z') {
        $gravite = 4;
        $error = "Code $from_code incorrect (doit commencer par une lettre)";
        return FALSE;
    }

    if ($ok_diagnostics_array !== TRUE) {
        $diagnostics_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_diagnostics ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $diagnostics_array[$code] = $oid;
            }
        }
        
        $ok_diagnostics_array = TRUE;
    }
    

    if ($ok_diagnostics_array === TRUE) {
        $oid = @$diagnostics_array[$from_code];
        if (get_num($oid) == 0) {
            $gravite = 0;
            $error = "Code $from_code inexistant";
            $commentaire = "Ce code sera créé";
            return FALSE;
        }
        
    }
    
    
    return TRUE;
    


}

function get_specialite_medecin($from_code) {

    global $iCTI_connexion;
    global $specialites_medecin_array;
    global $ok_specialites_medecin_array;
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    if ($ok_specialites_medecin_array !== TRUE) {
        $specialites_medecin_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_specialites_medecin ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $specialites_medecin_array[$code] = $oid;
            }
        }
        
        $ok_specialites_medecin_array = TRUE;
    }
    

    $oid = 0;
    if ($ok_specialites_medecin_array === TRUE) {
        $oid = @$specialites_medecin_array[$from_code];
        if (get_num($oid) > 0) {

        }
        else {
            $sqlcmd = "INSERT INTO pmsi.t_specialites_medecin( ";
            $sqlcmd = $sqlcmd . "code,  ";
            $sqlcmd = $sqlcmd . "texte,  ";
            $sqlcmd = $sqlcmd . "type  ";
            $sqlcmd = $sqlcmd . ") ";
            $sqlcmd = $sqlcmd . "VALUES( ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "''  ";
            $sqlcmd = $sqlcmd . ") ";
            
            $toResult = execute_sql($sqlcmd, $nbE, $nbW );
            
            $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_specialites_medecin WHERE code = '$from_code'");
            $ok = TRUE;
            while ($ok == TRUE) {
                $ok = FALSE;
                $record = pg_fetch_array($result);
                if ($record != FALSE) {
                    $ok = TRUE;
                    $code = trim($record["code"]);
                    $oid = $record["oid"];
                    $specialites_medecin_array[$code] = $oid;
                }
            }
            
        }
    }
    
    
    return $oid;
    


}

function check_specialite_medecin($from_code, &$gravite, &$error, &$commentaire) {

    global $iCTI_connexion;
    global $specialites_medecin_array;
    global $ok_specialites_medecin_array;
    
    $error = "";
    $commentaire = "";
    $gravite = 0;
    
        
    if ($ok_specialites_medecin_array !== TRUE) {
        $specialites_medecin_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_specialites_medecin ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $specialites_medecin_array[$code] = $oid;
            }
        }
        
        $ok_specialites_medecin_array = TRUE;
    }
    

    if ($ok_specialites_medecin_array === TRUE) {
        $oid = @$specialites_medecin_array[$from_code];
        if (get_num($oid) == 0) {
            $gravite = 0;
            $error = "Code $from_code inexistant";
            $commentaire = "Ce code sera créé";
            return FALSE;
        }
        
    }
    
    
    return TRUE;
    


}

function get_medecin($from_code) {

    global $iCTI_connexion;
    global $medecins_array;
    global $ok_medecins_array;
    
    
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    
    
    if ($ok_medecins_array !== TRUE) {
        $medecins_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_medecins ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $medecins_array[$code] = $oid;
            }
        }
        
        $ok_medecins_array = TRUE;
    }
    

    $oid = 0;
    if ($ok_medecins_array === TRUE) {
        $oid = @$medecins_array[$from_code];
        $from_code = toSQL($from_code);
        if (get_num($oid) > 0) {

        }
        else {
            $sqlcmd = "INSERT INTO pmsi.t_medecins( ";
            $sqlcmd = $sqlcmd . "code,  ";
            $sqlcmd = $sqlcmd . "nom,  ";
            $sqlcmd = $sqlcmd . "prenom,  ";
            $sqlcmd = $sqlcmd . "specialite_id,  ";
            $sqlcmd = $sqlcmd . "no_adeli,  ";
            $sqlcmd = $sqlcmd . "statut  ";
            $sqlcmd = $sqlcmd . ") ";
            $sqlcmd = $sqlcmd . "VALUES( ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "'',  ";
            $sqlcmd = $sqlcmd . "0, ";
            $sqlcmd = $sqlcmd . "'',  ";
            $sqlcmd = $sqlcmd . "''  ";
            $sqlcmd = $sqlcmd . ") ";
            
            $toResult = execute_sql($sqlcmd, $nbE, $nbW );
            
            $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_medecins WHERE code = '$from_code'");
            $ok = TRUE;
            while ($ok == TRUE) {
                $ok = FALSE;
                $record = pg_fetch_array($result);
                if ($record != FALSE) {
                    $ok = TRUE;
                    $code = trim($record["code"]);
                    $oid = $record["oid"];
                    $medecins_array[$code] = $oid;
                }
            }
            
        }
    }
    
    
    return $oid;
    


}


function get_comite_medical($from_code) {

    global $iCTI_connexion;
    global $comites_medicaux_array;
    global $ok_comites_medicaux_array;
    
    
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    
    
    if ($ok_comites_medicaux_array !== TRUE) {
        $comites_medicaux_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_comites_medicaux ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $comites_medicaux_array[$code] = $oid;
            }
        }
        
        $ok_comites_medicaux_array = TRUE;
    }
    

    $oid = 0;
    if ($ok_comites_medicaux_array === TRUE) {
        $oid = @$comites_medicaux_array[$from_code];
        if (get_num($oid) > 0) {

        }
        else {
            $sqlcmd = "INSERT INTO pmsi.t_comites_medicaux( ";
            $sqlcmd = $sqlcmd . "code,  ";
            $sqlcmd = $sqlcmd . "texte  ";
            $sqlcmd = $sqlcmd . ") ";
            $sqlcmd = $sqlcmd . "VALUES( ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "'$from_code'  ";
            $sqlcmd = $sqlcmd . ") ";
            
            $toResult = execute_sql($sqlcmd, $nbE, $nbW );
            
            $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_comites_medicaux WHERE code = '$from_code'");
            $ok = TRUE;
            while ($ok == TRUE) {
                $ok = FALSE;
                $record = pg_fetch_array($result);
                if ($record != FALSE) {
                    $ok = TRUE;
                    $code = trim($record["code"]);
                    $oid = $record["oid"];
                    $comites_medicaux_array[$code] = $oid;
                }
            }
            
        }
    }
    
    
    return $oid;
    


}



function get_code_postal($from_code) {

    global $iCTI_connexion;
    global $codes_postaux_array;
    global $ok_codes_postaux_array;
    
    
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    
    
    if ($ok_codes_postaux_array !== TRUE) {
        $codes_postaux_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM base.t_codes_postaux ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $codes_postaux_array[$code] = $oid;
            }
        }
        
        $ok_codes_postaux_array = TRUE;
    }
    

    $oid = 0;
    if ($ok_codes_postaux_array === TRUE) {
        $oid = @$codes_postaux_array[$from_code];
        if (get_num($oid) > 0) {
        
        }
        else {
            $oid = 0;
        }
    }
    
    
    return $oid;
    


}

function get_code_geographique_pmsi($from_code) {

    global $iCTI_connexion;
    global $codes_geographiques_pmsi_array;
    global $ok_codes_geographiques_pmsi_array;
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    if ($ok_codes_geographiques_pmsi_array !== TRUE) {
        $codes_geographiques_pmsi_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM base.t_codes_geographiques_pmsi ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $codes_geographiques_pmsi_array[$code] = $oid;
            }
        }
        $ok_codes_geographiques_pmsi_array = TRUE;
    }

    $oid = 0;
    if ($ok_codes_geographiques_pmsi_array === TRUE) {
        $oid = @$codes_geographiques_pmsi_array[$from_code];
        if (get_num($oid) < 1) {
            $oid = 0;
        }
    }
    return $oid;
}

function get_prestation($from_code) {

    global $iCTI_connexion;
    global $prestations_array;
    global $ok_prestations_array;
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    if ($ok_prestations_array !== TRUE) {
        $prestations_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_prestations ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $prestations_array[$code] = $oid;
            }
        }
        
        $ok_prestations_array = TRUE;
    }
    

    $oid = 0;
    if ($ok_prestations_array === TRUE) {
        $oid = @$prestations_array[$from_code];
        if (get_num($oid) > 0) {

        }
        else {
            $sqlcmd = "INSERT INTO pmsi.t_prestations( ";
            $sqlcmd = $sqlcmd . "code,  ";
            $sqlcmd = $sqlcmd . "texte,  ";
            $sqlcmd = $sqlcmd . "texte_court  ";
            $sqlcmd = $sqlcmd . ") ";
            $sqlcmd = $sqlcmd . "VALUES( ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "'$from_code'  ";
            $sqlcmd = $sqlcmd . ") ";
            
            $toResult = execute_sql($sqlcmd, $nbE, $nbW );
            
            $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_prestations WHERE code = '$from_code'");
            $ok = TRUE;
            while ($ok == TRUE) {
                $ok = FALSE;
                $record = pg_fetch_array($result);
                if ($record != FALSE) {
                    $ok = TRUE;
                    $code = trim($record["code"]);
                    $oid = $record["oid"];
                    $prestations_array[$code] = $oid;
                }
            }
            
        }
    }
    
    
    return $oid;
    


}

function check_medecin($from_code, &$gravite, &$error, &$commentaire) {

    global $iCTI_connexion;
    global $medecins_array;
    global $ok_medecins_array;
    
    $error = "";
    $commentaire = "";
    $gravite = 0;
    
    if (trim($from_code) == "") {
        $gravite = 4;
        $error = "Code médecin obligatoire";
        return FALSE;
    }
    
    
    if ($ok_medecins_array !== TRUE) {
        $medecins_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_medecins ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $medecins_array[$code] = $oid;
            }
        }
        
        $ok_medecins_array = TRUE;
    }
    

    if ($ok_medecins_array === TRUE) {
        $oid = @$medecins_array[$from_code];
        if (get_num($oid) == 0) {
            $gravite = 0;
            $error = "Code $from_code inexistant";
            $commentaire = "Ce code sera créé avec des valeurs par défaut";
            return FALSE;
        }
        
    }
    
    
    return TRUE;
    


}

function check_prestation($from_code, &$gravite, &$error, &$commentaire) {

    global $iCTI_connexion;
    global $prestations_array;
    global $ok_prestations_array;
    
    $error = "";
    $commentaire = "";
    $gravite = 0;
    
    if (trim($from_code) == "") {
        $gravite = 4;
        $error = "Code prestation obligatoire";
        return FALSE;
    }
    
    
    if ($ok_prestations_array !== TRUE) {
        $prestations_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_prestations ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $prestations_array[$code] = $oid;
            }
        }
        
        $ok_prestations_array = TRUE;
    }
    

    if ($ok_prestations_array === TRUE) {
        $oid = @$prestations_array[$from_code];
        if (get_num($oid) == 0) {
            $gravite = 0;
            $error = "Code $from_code inexistant";
            $commentaire = "Ce code sera créé";
            return FALSE;
        }
        
    }
    
    
    return TRUE;
    


}

function get_ghm($from_code) {

    global $iCTI_connexion;
    global $ghms_array;
    global $ok_ghms_array;
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    if ($ok_ghms_array !== TRUE) {
        $ghms_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_ghm ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $ghms_array[$code] = $oid;
            }
        }
        
        $ok_ghms_array = TRUE;
    }
    

    $oid = 0;
    // retourne l'oid 0 (Non renseigné) si le code GHM est mal formaté
    if (strlen(trim($from_code)) < 6)
        return $oid;
        
    if ($ok_ghms_array === TRUE) {
        $oid = @$ghms_array[$from_code];
        if (get_num($oid) > 0) {

        }
        else {
            $sqlcmd = "INSERT INTO pmsi.t_ghm( ";
            $sqlcmd = $sqlcmd . "code,  ";
            $sqlcmd = $sqlcmd . "texte,  ";
            $sqlcmd = $sqlcmd . "severite  ";
            $sqlcmd = $sqlcmd . ") ";
            $sqlcmd = $sqlcmd . "VALUES( ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "'*'  ";
            $sqlcmd = $sqlcmd . ") ";
            
            $toResult = execute_sql($sqlcmd, $nbE, $nbW );
            
            $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_ghm WHERE code = '$from_code'");
            $ok = TRUE;
            while ($ok == TRUE) {
                $ok = FALSE;
                $record = pg_fetch_array($result);
                if ($record != FALSE) {
                    $ok = TRUE;
                    $code = trim($record["code"]);
                    $oid = $record["oid"];
                    $ghms_array[$code] = $oid;
                }
            }
            
        }
    }
    
    
    return $oid;
    


}

function check_ghm($from_code, &$gravite, &$error, &$commentaire) {

    global $iCTI_connexion;
    global $ghms_array;
    global $ok_ghms_array;
    
    $error = "";
    $commentaire = "";
    $gravite = 0;
    
    if (strlen($from_code) != 6) {
        $gravite = 4;
        $error = "Code $from_code incorrect (longueur 6 obligatoire)";
        return FALSE;
    }
    
    // CMD ?
    if (! check_cmd(substr($from_code, 0, 2), $wgravite, $werreur)) {
        $gravite = 4;
        $error = "Code $from_code incorrect (CMD incorrecte)";
        return FALSE;
    }
    
    
    if ($ok_ghms_array !== TRUE) {
        $ghms_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_ghm ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $ghms_array[$code] = $oid;
            }
        }
        
        $ok_ghms_array = TRUE;
    }
    

    if ($ok_ghms_array === TRUE) {
        $oid = @$ghms_array[$from_code];
        if (get_num($oid) == 0) {
            $gravite = 4;
            $error = "Code $from_code inexistant";
            $commentaire = "Ce code ne peut être créé";
            return FALSE;
        }
        
    }
    
    
    return TRUE;
    


}

function check_cmd($from_code, &$gravite, &$error) {

    global $iCTI_connexion;
    global $cmds_array;
    global $ok_cmds_array;
    
    $error = "";
    $gravite = 0;
    
    if (strlen($from_code) != 2) {
        $gravite = 4;
        $error = "Code $from_code incorrect (longueur 2 obligatoire)";
        return FALSE;
    }
    
    
    if ($ok_cmds_array !== TRUE) {
        $cmds_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_cmd ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $cmds_array[$code] = $oid;
            }
        }
        
        $ok_cmds_array = TRUE;
    }
    

    if ($ok_cmds_array === TRUE) {
        $oid = @$cmds_array[$from_code];
        if (get_num($oid) == 0) {
            $gravite = 4;
            $error = "Code $from_code inexistant";
            return FALSE;
        }
        
    }
    
    
    return TRUE;
    


}

function get_ghs($from_code) {

    global $iCTI_connexion;
    global $ghss_array;
    global $ok_ghss_array;
    
    $oid = 0;
    
    $from_code = ltrim($from_code, '0');
    if ($from_code == "") {
        return $oid;
    }
    
    // if (! controle_check_num($from_code,0,FALSE,$werreur,$wcommentaire)) {
        // return $oid;
    // }
    $from_code = ltrim($from_code, '0');
    
    if ($ok_ghss_array !== TRUE) {
        $ghss_array = array();
        $result = $iCTI_connexion->query("SELECT code_text, oid FROM pmsi.t_ghs
									 UNION
									 SELECT code::text AS code_text, oid FROM pmsi.t_ghs WHERE code <> code_text ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code_text"]);
                $oid = $record["oid"];
                $ghss_array[$code] = $oid;
            }
        }
        
        $ok_ghss_array = TRUE;
    }
    

    $oid = 0;
    if ($ok_ghss_array === TRUE) {
        $oid = @$ghss_array[$from_code];
        if (get_num($oid) > 0) {

        }
        else {
            $sqlcmd = "INSERT INTO pmsi.t_ghs( ";
            $sqlcmd = $sqlcmd . "code,  ";
            $sqlcmd = $sqlcmd . "code_text,  ";
            $sqlcmd = $sqlcmd . "texte  ";
            $sqlcmd = $sqlcmd . ") ";
            $sqlcmd = $sqlcmd . "VALUES( ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "'$from_code'  ";
            $sqlcmd = $sqlcmd . ") ";
            
            $toResult = execute_sql($sqlcmd, $nbE, $nbW );
            
            $result = $iCTI_connexion->query("SELECT code_text, oid FROM pmsi.t_ghs WHERE code_text = $from_code");
            $ok = TRUE;
            while ($ok == TRUE) {
                $ok = FALSE;
                $record = pg_fetch_array($result);
                if ($record != FALSE) {
                    $ok = TRUE;
                    $code = trim($record["code_text"]);
                    $oid = $record["oid"];
                    $ghss_array[$code] = $oid;
                }
            }
            
        }
    }
    
    
    return $oid;
    


}

function check_ghs($from_code, &$gravite, &$error, &$commentaire) {

    global $iCTI_connexion;
    global $ghss_array;
    global $ok_ghss_array;
    
    $error = "";
    $commentaire = "";
    $gravite = 0;
    
    if ($from_code == "0000") {
        return TRUE;
    }
    else {
        $from_code = ltrim($from_code, '0');
    }
    
    
    
    // Désactivé car il existe des codes GHS non numériques (I01, D24, ...)
    // if (! controle_check_num($from_code,0,FALSE,$werreur,$wcommentaire)) {
        // $gravite = 4;
        // $error = "Code $from_code incorrect (non numérique)";
        // return FALSE;
    // }
    

    // if (strlen($from_code) < 4) {
        // $from_code = "0$from_code";
    // }
    // if (strlen($from_code) < 4) {
        // $from_code = "0$from_code";
    // }
    // if (strlen($from_code) < 4) {
        // $from_code = "0$from_code";
    // }
    
    // if (strlen($from_code) != 4) {
        // $gravite = 4;
        // $error = "Code $from_code incorrect (longueur 4 obligatoire)";
        // return FALSE;
    // }
    
    
    if ($ok_ghss_array !== TRUE) {
        $ghss_array = array();
        $result = $iCTI_connexion->query("SELECT code_text, oid FROM pmsi.t_ghs ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code_text"]);
                $oid = $record["oid"];
                $ghss_array[$code] = $oid;
            }
        }
        
        $ok_ghss_array = TRUE;
    }
    

    if ($ok_ghss_array === TRUE) {
        $oid = @$ghss_array[$from_code];
        if (get_num($oid) == 0) {
            $gravite = 0;
            $error = "Code $from_code inexistant";
            $commentaire = "Ce code sera créé";
            return FALSE;
        }
        
    }
    
    
    return TRUE;
    


}

function get_acte($from_code) {

    global $iCTI_connexion;
    global $actes_array;
    global $ok_actes_array;
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    if ($ok_actes_array !== TRUE) {
        $actes_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_actes ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $actes_array[$code] = $oid;
            }
        }
        
        $ok_actes_array = TRUE;
    }
    

    $oid = 0;
    if ($ok_actes_array === TRUE) {
        $oid = @$actes_array[$from_code];
        if (get_num($oid) > 0) {

        }
        else {
            $sqlcmd = "INSERT INTO pmsi.t_actes( ";
            $sqlcmd = $sqlcmd . "code,  ";
            $sqlcmd = $sqlcmd . "texte,  ";
            $sqlcmd = $sqlcmd . "texte_court,  ";
            $sqlcmd = $sqlcmd . "nomenclature  ";
            $sqlcmd = $sqlcmd . ") ";
            $sqlcmd = $sqlcmd . "VALUES( ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "'CCAM'  ";
            $sqlcmd = $sqlcmd . ") ";
            
            $toResult = execute_sql($sqlcmd, $nbE, $nbW );
            
            $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_actes WHERE code = '$from_code'");
            $ok = TRUE;
            while ($ok == TRUE) {
                $ok = FALSE;
                $record = pg_fetch_array($result);
                if ($record != FALSE) {
                    $ok = TRUE;
                    $code = trim($record["code"]);
                    $oid = $record["oid"];
                    $actes_array[$code] = $oid;
                }
            }
            
        }
    }
    
    return $oid;
    


}

function check_acte($from_code, &$gravite, &$error, &$commentaire) {

    global $iCTI_connexion;
    global $actes_array;
    global $ok_actes_array;
    
    $error = "";
    $commentaire = "";
    $gravite = 0;
    
    if (strlen($from_code) != 7 && strlen($from_code) != 10) {
        $gravite = 4;
        $error = "Code $from_code incorrect (longueur 7 obligatoire ou 10 si CCAM descriptive)";
        return FALSE;
    }
    
    
    
    if ($ok_actes_array !== TRUE) {
        $actes_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_actes ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $actes_array[$code] = $oid;
            }
        }
        
        $ok_actes_array = TRUE;
    }
    

    if ($ok_actes_array === TRUE) {
        $oid = @$actes_array[$from_code];
        if (get_num($oid) == 0) {
            $gravite = 0;
            $error = "Code $from_code inexistant";
            $commentaire = "Ce code sera créé";
            return FALSE;
        }
        
    }
    
    
    return TRUE;
    


}

function check_regime($from_code, &$gravite, &$error, &$commentaire) {

    global $iCTI_connexion;
    global $regime_array;
    global $ok_regime_array;
    
    $error = "";
    $commentaire = "";
    $gravite = 0;
    
    if ($ok_regime_array !== TRUE) {
        $regime_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM base.t_grands_regimes");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $regime_array[$code] = $oid;
            }
        }
        $ok_regime_array = TRUE;
    }

    if ($ok_regime_array === TRUE) {
        $oid = @$regime_array[$from_code];
        if (get_num($oid) == 0) {
            $gravite = 0;
            $error = "Code $from_code inexistant";
            $commentaire = "Ce code sera créé";
            return FALSE;
        }
    }
    return TRUE;
}

function check_exoneration_tm($from_code, &$gravite, &$error, &$commentaire) {

    global $iCTI_connexion;
    global $exoneration_tm_array;
    global $ok_exoneration_tm_array;
    
    $error = "";
    $commentaire = "";
    $gravite = 0;
    
    if ($ok_exoneration_tm_array !== TRUE) {
        $exoneration_tm_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM base.t_exoneration_tm");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $exoneration_tm_array[$code] = $oid;
            }
        }
        $ok_exoneration_tm_array = TRUE;
    }

    if ($ok_exoneration_tm_array === TRUE) {
        $oid = @$exoneration_tm_array[$from_code];
        if (get_num($oid) == 0) {
            $gravite = 0;
            $error = "Code $from_code inexistant";
            $commentaire = "Ce code sera créé";
            return FALSE;
        }
    }
    return TRUE;
}

function check_nature_pec($from_code, &$gravite, &$error, &$commentaire) {

    global $iCTI_connexion;
    global $nature_pec_array;
    global $ok_nature_pec_array;
    
    $error = "";
    $commentaire = "";
    $gravite = 0;
    
    if ($ok_nature_pec_array !== TRUE) {
        $nature_pec_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM base.t_nature_assurance");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $nature_pec_array[$code] = $oid;
            }
        }
        $ok_nature_pec_array = TRUE;
    }

    if ($ok_nature_pec_array === TRUE) {
        $oid = @$nature_pec_array[$from_code];
        if (get_num($oid) == 0) {
            $gravite = 0;
            $error = "Code $from_code inexistant";
            $commentaire = "Ce code sera créé";
            return FALSE;
        }
    }
    return TRUE;
}

function get_lpp($from_code) {

    global $iCTI_connexion;
    global $lpp_array;
    global $ok_lpp_array;
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    if ($ok_lpp_array !== TRUE) {
        $lpp_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_lpp ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $lpp_array[$code] = $oid;
            }
        }
        $ok_lpp_array = TRUE;
    }
    

    $oid = 0;
    if ($ok_lpp_array === TRUE) {
        $oid = @$lpp_array[$from_code];
        if (get_num($oid) > 0) {

        }
        else {
            $sqlcmd = "INSERT INTO pmsi.t_lpp( ";
            $sqlcmd = $sqlcmd . "code,  ";
            $sqlcmd = $sqlcmd . "texte,  ";
            $sqlcmd = $sqlcmd . "texte_court  ";
            $sqlcmd = $sqlcmd . ") ";
            $sqlcmd = $sqlcmd . "VALUES( ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "'$from_code'  ";
            $sqlcmd = $sqlcmd . ") ";
            
            $toResult = execute_sql($sqlcmd, $nbE, $nbW );
            
            $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_lpp WHERE code = '$from_code'");
            $ok = TRUE;
            while ($ok == TRUE) {
                $ok = FALSE;
                $record = pg_fetch_array($result);
                if ($record != FALSE) {
                    $ok = TRUE;
                    $code = trim($record["code"]);
                    $oid = $record["oid"];
                    $lpp_array[$code] = $oid;
                }
            }
            
        }
    }
    
    return $oid;
    


}

function check_lpp($from_code, &$gravite, &$error, &$commentaire) {

    global $iCTI_connexion;
    global $lpps_array;
    global $ok_lpps_array;
    
    $error = "";
    $commentaire = "";
    $gravite = 0;
    
    
    if ($ok_lpps_array !== TRUE) {
        $lpps_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_lpp ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $lpps_array[$code] = $oid;
            }
        }
        
        $ok_lpps_array = TRUE;
    }
    

    if ($ok_lpps_array === TRUE) {
        $oid = @$lpps_array[get_num($from_code)];
        if (get_num($oid) == 0) {
            $gravite = 0;
            $error = "Code $from_code inexistant";
            $commentaire = "Ce code sera créé";
            return FALSE;
        }
        
    }
    
    
    return TRUE;
    


}


function get_ucd($from_code) {

    global $iCTI_connexion;
    global $ucd_array;
    global $ok_ucd_array;
    
    $oid = 0;
    
    if ($from_code == "") {
        return $oid;
    }
    
    $from_code = trim(get_num($from_code));
    
    if ($ok_ucd_array !== TRUE) {
        $ucd_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_ucd ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $ucd_array[$code] = $oid;
            }
        }
        $ok_ucd_array = TRUE;
    }
    

    $oid = 0;
    if ($ok_ucd_array === TRUE) {
        $oid = @$ucd_array[$from_code];
        if (get_num($oid) > 0) {

        }
        else {
            $sqlcmd = "INSERT INTO pmsi.t_ucd( ";
            $sqlcmd = $sqlcmd . "code,  ";
            $sqlcmd = $sqlcmd . "texte,  ";
            $sqlcmd = $sqlcmd . "texte_court  ";
            $sqlcmd = $sqlcmd . ") ";
            $sqlcmd = $sqlcmd . "VALUES( ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "'$from_code'  ";
            $sqlcmd = $sqlcmd . ") ";
            
            $toResult = execute_sql($sqlcmd, $nbE, $nbW );
            
            $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_ucd WHERE code = '$from_code'");
            $ok = TRUE;
            while ($ok == TRUE) {
                $ok = FALSE;
                $record = pg_fetch_array($result);
                if ($record != FALSE) {
                    $ok = TRUE;
                    $code = trim($record["code"]);
                    $oid = $record["oid"];
                    $ucd_array[$code] = $oid;
                }
            }
            
        }
    }
    
    return $oid;
    


}

function get_finess($from_code) {

    global $iCTI_connexion;
    global $fin_array;
    global $ok_fin_array;
    
    $oid = 0;
    
    if ($from_code == "" || get_num($from_code) == 0) {
        return $oid;
    }
    
    $from_code = str_pad(trim(get_num($from_code)), 9, "0", STR_PAD_LEFT);
    
    if ($ok_fin_array !== TRUE) {
        $fin_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM base.t_etablissements ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = trim($record["code"]);
                $oid = $record["oid"];
                $fin_array[$code] = $oid;
            }
        }
        $ok_fin_array = TRUE;
    }
    

    $oid = 0;
    if ($ok_fin_array === TRUE) {
        $oid = @$fin_array[$from_code];
        if (get_num($oid) > 0) {

        }
        else {
            $sqlcmd = "INSERT INTO base.t_etablissements( ";
            $sqlcmd = $sqlcmd . "code,  ";
            $sqlcmd = $sqlcmd . "texte,  ";
            $sqlcmd = $sqlcmd . "texte_court  ";
            $sqlcmd = $sqlcmd . ") ";
            $sqlcmd = $sqlcmd . "VALUES( ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "'$from_code',  ";
            $sqlcmd = $sqlcmd . "'$from_code'  ";
            $sqlcmd = $sqlcmd . ") ";
            
            $toResult = execute_sql($sqlcmd, $nbE, $nbW );
            
            $result = $iCTI_connexion->query("SELECT code, oid FROM base.t_etablissements WHERE code = '$from_code'");
            $ok = TRUE;
            while ($ok == TRUE) {
                $ok = FALSE;
                $record = pg_fetch_array($result);
                if ($record != FALSE) {
                    $ok = TRUE;
                    $code = trim($record["code"]);
                    $oid = $record["oid"];
                    $fin_array[$code] = $oid;
                }
            }
            
        }
    }
    
    return $oid;
    


}

function check_ucd($from_code, &$gravite, &$error, &$commentaire) {

    global $iCTI_connexion;
    global $ucds_array;
    global $ok_ucds_array;
    
    $error = "";
    $commentaire = "";
    $gravite = 0;
    
    $from_code = get_num($from_code);
    
    
    if ($ok_ucds_array !== TRUE) {
        $ucds_array = array();
        $result = $iCTI_connexion->query("SELECT code, oid FROM pmsi.t_ucd ");
        $ok = TRUE;
        while ($ok == TRUE) {
            $ok = FALSE;
            $record = pg_fetch_array($result);
            if ($record != FALSE) {
                $ok = TRUE;
                $code = get_num(trim($record["code"]));
                $oid = $record["oid"];
                $ucds_array[$code] = $oid;
            }
        }
        
        $ok_ucds_array = TRUE;
    }
    

    if ($ok_ucds_array === TRUE) {
        $oid = @$ucds_array[get_num($from_code)];
        if (get_num($oid) == 0) {
            $gravite = 0;
            $error = "Code $from_code inexistant";
            $commentaire = "Ce code sera créé";
            return FALSE;
        }
        
    }
    
    
    return TRUE;
    


}


function check_complog_fichcomp($buffer, &$gravite, &$error, &$commentaire) {

    global $iCTI_connexion;
    
    $error = "";
    $commentaire = "";
    $gravite = 0;
    
    $bufferx = str_replace(" ","",$buffer);
    $bufferx = str_replace(";","",$bufferx);
    
    $sqlcmd = "SELECT data FROM w_out_complog 
        WHERE substr(replace(replace(data,';',''),' ',''),10,2) IN ('02','06','09','15') AND 
        '" . trim($bufferx) . "' LIKE '%' || replace(replace(data,';',''),' ','') || '%'";
    $result = $iCTI_connexion->query($sqlcmd);
    $ok = TRUE;
    while ($ok == TRUE) {
        $ok = FALSE;
        $record = pg_fetch_array($result);
        if ($record != FALSE) {
            $gravite = 1;
            $error = "La ligne n'est pas acceptée par GENRSA";
            $commentaire = "";
            return FALSE;
        }
    }
        
    
    return TRUE;
    


}

function sqlDate($BUF_date) {

    $date_AAAAMMJJ = get_date_AAAAMMJJ($BUF_date);

    $year = substr($date_AAAAMMJJ, 0, 4);
    $month = substr($date_AAAAMMJJ, 4, 2);
    $day = substr($date_AAAAMMJJ, 6, 2);
    
    if (floatval($year) < 1850) {
        $year = 1962;
    }

    $sqlDate = "$year$month$day";
    
    return $sqlDate;
}



function generation_donnees_complementaires($workschema="temp", $node="PMSICOMPLEMENTS") {

global $ENV_PMSIPROVIDER;
global $ENV_PMSIPROVIDER2;
global $ENV_ADMPROVIDER;

    

    $w_ENV_PMSIPROVIDER = $ENV_PMSIPROVIDER;
    $w_ENV_ADMPROVIDER = $ENV_ADMPROVIDER;
    
    if ($ENV_PMSIPROVIDER2 != ''){
        logInfoMsg("Traitement complémentaire ancien prestataire $ENV_PMSIPROVIDER2");

        switch($ENV_PMSIPROVIDER2) {
            case "cegi" :
                generation_donnees_complementaires_execute($workschema, $node, "CEGI");
                break;
            case "clinicom" :
                generation_donnees_complementaires_execute($workschema, $node, "CLINICOM");
                break;
            case "cora" :
                generation_donnees_complementaires_execute($workschema, $node, "CORA");
                break;
            case "csis" :
                generation_donnees_complementaires_execute($workschema, $node, "CSIS");
                break;
            case "hemat2a" :
                generation_donnees_complementaires_execute($workschema, $node, "HEMAT2A");
                break;
            case "r2i" :
            case "hm" :
                generation_donnees_complementaires_execute($workschema, $node, "HM");
                break;
            case "mipih" :
                generation_donnees_complementaires_execute($workschema, $node, "MIPIH");
                break;
            case "orbis" :
                generation_donnees_complementaires_execute($workschema, $node, "ORBIS");
                break;
            case "sim" :
                generation_donnees_complementaires_execute($workschema, $node, "SIM");
                break;
            case "qsp" :
                generation_donnees_complementaires_execute($workschema, $node, "QSP");
                break;
            case "shs" :
                generation_donnees_complementaires_execute($workschema, $node, "SHS");
                break;
            case "sigems" :
                generation_donnees_complementaires_execute($workschema, $node, "SIGEMS");
                break;
            case "sigems2" :
                generation_donnees_complementaires_execute($workschema, $node, "SIGEMS2");
                break;
            case "web100t" :
                if ($ENV_PMSIPROVIDER2 != "mipih" && $ENV_PMSIPROVIDER2 != "shs") {
                    generation_donnees_complementaires_execute($workschema, $node, "WEB100T");
                }
                break;
            case "web100t2" :
                generation_donnees_complementaires_execute($workschema, $node, "WEB100T2");
                break;
            case "baclessepmsi" :
                generation_donnees_complementaires_execute($workschema, $node, "BACLESSEPMSI");
                break;
            case "mederi" :
                generation_donnees_complementaires_execute($workschema, $node, "MEDERI");
                break;
            case "evolucare_opale" :
                generation_donnees_complementaires_execute($workschema, $node, "EVOLUCARE_OPALE");
                break;
            default :
                logWarnMsg('Traitement complémentaire non trouvé.');
        }
    }

    logInfoMsg("Traitement complémentaire prestataire $w_ENV_PMSIPROVIDER");
    switch($w_ENV_PMSIPROVIDER) {

        case "cegi" :
            generation_donnees_complementaires_execute($workschema, $node, "CEGI");
            break;
        case "clinicom" :
            generation_donnees_complementaires_execute($workschema, $node, "CLINICOM");
            break;
        case "cora" :
            generation_donnees_complementaires_execute($workschema, $node, "CORA");
            break;
        case "csis" :
            generation_donnees_complementaires_execute($workschema, $node, "CSIS");
            break;
		case "hemat2a" :
            generation_donnees_complementaires_execute($workschema, $node, "HEMAT2A");
            break;
        case "r2i" :
        case "hm" :
            generation_donnees_complementaires_execute($workschema, $node, "HM");
            break;
        case "mipih" :
            generation_donnees_complementaires_execute($workschema, $node, "MIPIH");
            break;
        case "orbis" :
            generation_donnees_complementaires_execute($workschema, $node, "ORBIS");
            break;
        case "sim" :
            generation_donnees_complementaires_execute($workschema, $node, "SIM");
            break;
        case "qsp" :
            generation_donnees_complementaires_execute($workschema, $node, "QSP");
            break;
        case "shs" :
            generation_donnees_complementaires_execute($workschema, $node, "SHS");
            break;
        case "sigems" :
            generation_donnees_complementaires_execute($workschema, $node, "SIGEMS");
            break;
        case "sigems2" :
            generation_donnees_complementaires_execute($workschema, $node, "SIGEMS2");
            break;
        case "web100t" :
            if ($w_ENV_ADMPROVIDER != "mipih" && $w_ENV_ADMPROVIDER != "shs") {
                generation_donnees_complementaires_execute($workschema, $node, "WEB100T");
            }
            break;
        case "web100t2" :
            generation_donnees_complementaires_execute($workschema, $node, "WEB100T2");
            break;
        case "baclessepmsi" :
            generation_donnees_complementaires_execute($workschema, $node, "BACLESSEPMSI");
            break;
        case "mederi" :
            generation_donnees_complementaires_execute($workschema, $node, "MEDERI");
            break;
        case "evolucare_opale" :
            generation_donnees_complementaires_execute($workschema, $node, "EVOLUCARE_OPALE");
            break;
        default :
            logWarnMsg('Traitement complémentaire non trouvé.');
    }

    // Spécifique CEGI (LOGHOS) pour les externes
    if ($w_ENV_PMSIPROVIDER == "cegi" && $w_ENV_ADMPROVIDER == "cegi") {
        $sql = "
            SELECT *
            FROM information_schema.tables
            WHERE 1=1
            AND table_schema = 'prod_cegiloghos'
        ";
        $res = execute_sql($sql);
        if (pg_num_rows($res) > 0) {
            logInfoMsg("Mise à jour des externes depuis CEGILOGHOS");
            generation_donnees_complementaires_execute($workschema, $node, "CEGILOGHOS");
        }   
    }
    // Spécifique cerner pour les externes (St joseph St Luc / Hopital suisse / HP Metz)
    if (($w_ENV_PMSIPROVIDER == "sim" || $w_ENV_PMSIPROVIDER == "evolucare_opale" || $w_ENV_PMSIPROVIDER == "web100t") && $w_ENV_ADMPROVIDER == "cerner") {
        generation_donnees_complementaires_execute($workschema, $node, "CERNER");
    }

}

function generation_donnees_complementaires_execute($workschema, $node, $provider) {

    global $iCTI_connexion;
    global $import_id;
    global $ENV_FINESS;
    global $annee_fin;

    begin_trans();

    $idEtablissement = '';
    $SHS_pmsischema = '';
    $SHS_activiteschema = '';

    $file = __ROOT__ . "/settings/databases/$provider.XML";
    $xml = simplexml_load_string(file_get_contents($file));

    if ($provider === "HM" || $provider === "CEGI" ) {
        $idEtablissement = isset($xml['idEtablissement']) ? trim($xml['idEtablissement']) : '';
    }

    if ($provider === "SHS") {
        $SHS_pmsischema = isset($xml['pmsilib']) ? trim($xml['pmsilib']) : '';
        $SHS_activiteschema = isset($xml['admlib']) ? trim($xml['admlib']) : '';
    }

    $import_annee = $annee_fin;
    if (strlen($import_annee) != 4) {
        $import_annee = '2099';
    }

    // Chargement requetes SQL
    $environmentVars=array();
    $environmentVars["SCHEMA"] = $workschema;
    $environmentVars["IMPORT_ID"] = $import_id;
    $environmentVars["PMSISCHEMA"] = $SHS_pmsischema;
    $environmentVars["ACTIVITESCHEMA"] = $SHS_activiteschema;
    $environmentVars["HM_PMSI_PRATCOD_FIELD"] = "MEDE_CODE";
    $environmentVars["ETAB"] = $idEtablissement;
    $environmentVars["FINESS"] = $ENV_FINESS;
    $environmentVars["IMPORT_ANNEE"] = $import_annee;

    $sqlOptions=array();

    $providerFile = __ROOT__ . "/modules/pmsi/import_rss_rsf/iCTI_import_pmsi_$provider.XML";
    $cti_sqlStatements = new CTI_SqlStatements_class($providerFile, $iCTI_connexion, $environmentVars, $sqlOptions);

    // Exécution requetes SQL

    $cti_sqlStatements->executeStatementsNode($node);

    commit_trans();
}

function addFile($data_type, $data_path) {


    global $import_id;

    
    if (file_exists($data_path)) {
    
        $sqlcmd = "DELETE FROM pmsi.p_imports_data WHERE import_id = $import_id AND data_type = '$data_type' ";
        $result =  execute_sql($sqlcmd);
        
        $file_size = filesize($data_path);
        $file_path = "";
        $data_crc = "";

        $start = 0;
        $data_num = 0;
        
        while ($start <= $file_size) {
            $filebuff = file_get_contents($data_path, FALSE, NULL, $start, 10000000);
            
            $filebuff = pg_escape_bytea(compress64($filebuff));
            
            $sqlcmd = "INSERT INTO pmsi.p_imports_data (import_id, data_type, date_creation, data_num, data, file_path, file_size, data_crc) ";
            $sqlcmd = $sqlcmd . "VALUES($import_id, '$data_type', '2099-12-31', $data_num, '$filebuff', '$file_path', $file_size, '$data_crc' )";
            $result =  execute_sql($sqlcmd);
            
            $start = $start + 10000000;
            $data_num++;
        }
    }

}


function disable_index($indexName, $schema="pmsi") {

    global $iCTI_connexion;

    $sqlcmd = "SELECT base.cti_disable_index('$schema', '$indexName')";
    $toResult = $iCTI_connexion->query($sqlcmd);
    
    commit_trans();
    
    
}

function enable_index($indexName, $schema="pmsi") {

    global $iCTI_connexion;

    $sqlcmd = "SELECT base.cti_enable_index('$schema', '$indexName')";
    $toResult = $iCTI_connexion->query($sqlcmd);
    
    commit_trans();
    
    
}


function vacuum_tables() {

    logInfoMsg("REORGANISATION BASE DE DONNEES");

    end_trans();
    vacuum_table("t_medecins");
    vacuum_table("p_chiffrier");
    vacuum_table("p_patients");
    vacuum_table("p_identites");
    vacuum_table("p_rss");
    vacuum_table("p_rsf_total");
    vacuum_table("p_rsf_detail");
    vacuum_table("p_rsf_detail_h");
    vacuum_table("p_rss_rum");
    vacuum_table("p_rss_diagnostics");
    vacuum_table("p_rss_actes");
    vacuum_table("p_rss_lpp");
    vacuum_table("p_rss_leg");
    vacuum_table("p_rss_maternite");
    vacuum_table("p_rsa");
    vacuum_table("p_vidhosp");
    vacuum_table("p_vidhosp_crc");
    vacuum_table("p_oids");
    
    
    logInfoMsg("FIN REORGANISATION BASE DE DONNEES");
}


function analyse_all_tables() {

    global $iCTI_connexion;
    
    logInfoMsg("Recréation statistiques base de données");
    
    end_trans();
    
    $toResult = $iCTI_connexion->query("ANALYSE");
    if ($toResult == FALSE) {
        logErrorMsg("Erreur ANALYSE");
    }

}

function analyse_tables() {

    logInfoMsg("Analyse base de données");

    end_trans();
    analyse_table("t_medecins");
    analyse_table("p_chiffrier");
    analyse_table("p_identites");
    analyse_table("p_patients");
    analyse_table("p_rss");
    analyse_table("p_rsf_total");
    analyse_table("p_rsf_detail");
    analyse_table("p_rsf_detail_h");
    analyse_table("p_rss_rum");
    analyse_table("p_rss_diagnostics");
    analyse_table("p_rss_actes");
    analyse_table("p_rss_lpp");
    analyse_table("p_rss_leg");
    analyse_table("p_rss_maternite");
    analyse_table("p_rsa");
    analyse_table("p_vidhosp");
    analyse_table("p_vidhosp_crc");
    analyse_table("p_oids");
    

    
}



function begin_trans() {

    global $iCTI_connexion;
    global $nbtrans;
    global $trans_sqlcmd_array;

    $toResult = $iCTI_connexion->query("BEGIN;");

    $nbtrans = 0;
    $trans_sqlcmd_array = array();

}

function add_trans($sqlcmd) {

    global $iCTI_connexion;
    global $nbtrans;
    global $trans_sqlcmd_array;
    
    $nbtrans++;
    $trans_sqlcmd_array[$nbtrans] = $sqlcmd;
    
    if ($nbtrans >= 1000) {
        commit_trans();
        begin_trans();
    }

}

function commit_trans() {

    global $iCTI_connexion;
    global $nbtrans;
    global $trans_sqlcmd_array;
    
    $toResult = $iCTI_connexion->query("COMMIT;");

    $nbtrans = 0;
    $trans_sqlcmd_array = array();
}

function end_trans() {

    global $iCTI_connexion;
    global $nbtrans;
    global $trans_sqlcmd_array;
    
    $toResult = $iCTI_connexion->query("COMMIT;");

    $nbtrans = 0;
    $trans_sqlcmd_array = array();
}

function rollback_trans() {

    global $iCTI_connexion;
    global $nbtrans;
    global $trans_sqlcmd_array;
    
    $toResult = $iCTI_connexion->query("ROLLBACK;");
    
    
    foreach ($trans_sqlcmd_array as $sqlcmd) {
        $toResult = @$iCTI_connexion->query($sqlcmd);
    }


    
    begin_trans();
}






function csv2array($input,$delimiter=',',$enclosure='"',$escape='\\'){
    $fields=explode($enclosure.$delimiter.$enclosure,substr($input,1,-1));
    foreach ($fields as $key=>$value){
        $fields[$key]=str_replace($escape.$enclosure,$enclosure,$value);
    }
    return($fields);
}

/**
 * Sorte d'override de la fonciton native in_array($needle, $haystack) où
 * on controle en plus que $haystack est bien un tableau
 */
function cti_in_array($needle, $haystack) {
    if (is_array($haystack)) {
        return in_array($needle, $haystack);
    }
    else {
        return false;
    }
}

/**
 * Traitements de fin 
 */

/**
 * Marquage des séjours selon les critères des Indicateurs de Pilotage des Activités de soins autorisés (IPA)
 */
function estampillage_ipa() {

    global $iCTI_connexion;

    logInfoMsg("Estampillage IPA");
    
    $toResult = $iCTI_connexion->query("SELECT pmsi.cti_gen_ipa()");
    commit_trans();
    if ($toResult == FALSE) {
        logErrorMsg("Erreur SELECT pmsi.cti_gen_ipa()");
    }

}


/**
 * Marquage des séjours selon les prestations de SRC
 */
function set_etudes() {

    global $iCTI_connexion;

    logInfoMsg("Etudes. Impact CMA");
    
    $toResult = $iCTI_connexion->query("SELECT pmsi.cti_etude_impact_cma()");
    commit_trans();
    if ($toResult == FALSE) {
        logErrorMsg("Erreur SELECT pmsi.cti_etude_impact_cma()");
    }

}

/**
 * Marquage des séjours selon les prestations de SRC
 */
function set_src() {

    global $iCTI_connexion;

    logInfoMsg("Estampillage SRC");
    
    $toResult = $iCTI_connexion->query("SELECT pmsi.cti_gen_src()");
    commit_trans();
    if ($toResult == FALSE) {
        logErrorMsg("Erreur SELECT pmsi.cti_gen_src()");
    }

}

/**
 * Marquage des séjours selon les prestations de REA
 */
function set_rea() {

    global $iCTI_connexion;

    logInfoMsg("Estampillage REA");
    
    $toResult = $iCTI_connexion->query("SELECT pmsi.cti_gen_rea()");
    commit_trans();
    if ($toResult == FALSE) {
        logErrorMsg("Erreur SELECT pmsi.cti_gen_rea()");
    }

}
    
/**
 * Association des séjours avec les gestes marqueurs
 */
function set_gestes_marqueurs() {

    global $iCTI_connexion;

    logInfoMsg("Gestes marqueurs");
    
    $toResult = $iCTI_connexion->query("SELECT pmsi.cti_gen_gm()");
    commit_trans();
    if ($toResult == FALSE) {
        logErrorMsg("Erreur SELECT pmsi.cti_gen_gm()");
    }

}


/**
 * Extraction données Cancéro
 */
function set_cancero() {

    global $iCTI_connexion;

    logInfoMsg("Cancérologie");
    
    $toResult = $iCTI_connexion->query("SELECT pmsi.cti_gen_cancero_2017()");
    execute_etude("CTI_CANCERO_2022");    
    commit_trans();
    if ($toResult == FALSE) {
        logErrorMsg("Erreur SELECT pmsi.cti_gen_cancero_2017()");
    }

}

/**
 * Extraction données Cardio
 */
function set_etude_cardio() {

    logInfoMsg("Cardiologie");

    execute_etude("CTI_CARDIO_INTERVENTIONNELLE_2022");
}

/**
 * Extraction donées Cancéro
 */
function set_sae() {

    global $iCTI_connexion;
    global $import_id;

    logInfoMsg("Indicateurs RSS SAE");
    
    $toResult = $iCTI_connexion->query("SELECT pmsi.cti_gen_sae($import_id)");
    commit_trans();
    if ($toResult == FALSE) {
        logErrorMsg("Erreur SELECT pmsi.cti_gen_sae($import_id)");
    }

}


/**
 * Calcul d'indicateurs liés à la maternité
 */
function set_maternite() {

    global $iCTI_connexion;
    global $import_id;

    logInfoMsg("Indicateurs Maternité");
    
    $toResult = $iCTI_connexion->query("SELECT pmsi.cti_gen_maternite('temp', $import_id)");
    commit_trans();
    if ($toResult == FALSE) {
        logErrorMsg("Erreur SELECT pmsi.cti_gen_maternite('temp', $import_id)");
    }

}


/**
 * Execution règles expert
 */
function expert_execute_rules() {

    global $iCTI_connexion;

    logInfoMsg("Exécution règles EXPERT");
    
    $toResult = $iCTI_connexion->query("SELECT pmsi.cti_expert_execute_rules()");
    commit_trans();
    if ($toResult == FALSE) {
        logErrorMsg("Erreur SELECT pmsi.cti_expert_execute_rules()");
    }else { 
			$record = pg_fetch_array($toResult); 
			$resultat = $record["cti_expert_execute_rules"]; 
			logInfoMsg($resultat); 
	}

}


/**
 * Extraction état dossier
 */
function get_etat_dossier() {

    global $iCTI_connexion;
    global $omitComplements;

    logInfoMsg("Exécution état dossier");
    $toResult = $iCTI_connexion->query("SELECT pmsi.cti_initialize_rss_etat()");
    if ($omitComplements == false) {
        generation_donnees_complementaires("pmsi", "PMSIETAT");
    }
    else {
        logInfoMsg("Omission données complémentaires : Etat des dossiers");
    }
    

}


function stats_mat2a($import_id=-1) {

    global $iCTI_connexion;

    logInfoMsg("Stats MAT2A");
    
    $toResult = $iCTI_connexion->query("SELECT pmsi.cti_imports_calc_stats($import_id)");
    commit_trans();
    if ($toResult == FALSE) {
        logErrorMsg("Erreur SELECT pmsi.cti_imports_calc_stats($import_id)");
    }
    
}


    
?>
