From 8b5b16f9f737d8a406a53f06907b2bfac3d54752 Mon Sep 17 00:00:00 2001
From: alex <alex@c028cbd2-c16b-5b4b-a496-9718f37d4682>
Date: Mon, 16 May 2005 23:44:23 +0000
Subject: [PATCH] Patch level         : 2.2 101 Files correlati     :
 Ricompilazione Demo : [ ] Commento            :

Riportata la versione 2.1 300


git-svn-id: svn://10.65.10.50/trunk@13091 c028cbd2-c16b-5b4b-a496-9718f37d4682
---
 ba/ba3100.cpp                     |   45 +-
 ba/ba3800.cpp                     |  853 ++++++++++-------------
 ba/ba4300.h                       |    3 +
 ba/ba4300a.uml                    |   88 ++-
 ba/bacnv.cpp                      |   74 +-
 ba/bastivd.uml                    |   21 +-
 ba/batbivd.uml                    |   15 +-
 ba/batbreg.h                      |    3 +
 ba/batbreg.uml                    |   34 +-
 ba/cgarea.men                     |    4 +-
 ba/f9.dir                         |    2 +-
 ba/f9.trr                         |    4 +-
 ce/ce1500.cpp                     |    2 +-
 ce/ce1500a.uml                    |   51 +-
 ce/ce2200.cpp                     |   25 +-
 cg/cg0100.cpp                     |    4 +-
 cg/cg0100a.uml                    |   84 ++-
 cg/cg1100.cpp                     |  467 ++++---------
 cg/cg3200.cpp                     |   92 +--
 cg/cg3400.cpp                     |    2 +-
 cg/cg5800a.frm                    |  306 +++------
 cg/cg5800b.uml                    |    2 +-
 cg/cg5800ra.rep                   |    3 +-
 cg/cg7200.cpp                     |  163 ++++-
 cg/cgp4.cpp                       |    2 +
 cg/f19.dir                        |    2 +-
 cg/f19.trr                        |    4 +-
 cg/proforma.ini                   |   39 +-
 cm/cm0100.cpp                     |   68 +-
 cm/cm0100a.frm                    |   12 +-
 cm/cm0200.cpp                     |   71 +-
 cm/cm0200a.frm                    |   10 +-
 db/db1100.cpp                     |   19 +-
 ef/ef0300.cpp                     |    2 +
 ef/ef0300a.uml                    |    1 +
 include/alex.cpp                  |   37 +-
 include/colors.h                  |    2 +
 include/controls.cpp              |  183 ++---
 include/dongle.cpp                |    7 +-
 include/execp.cpp                 |   24 +-
 include/isam.cpp                  |   10 +
 include/isam.h                    |   18 +-
 include/isamrpc.cpp               |    4 +-
 include/isamrpc.h                 |    2 +-
 include/maskfld.cpp               |   83 ++-
 include/modaut.h                  |    2 +-
 include/msksheet.cpp              |   21 +-
 include/printer.cpp               |    6 +-
 include/recset.cpp                |   67 +-
 include/report.cpp                |   59 +-
 include/report.h                  |   19 +-
 include/reprint.cpp               |    4 +-
 include/sheet.cpp                 |   46 +-
 include/sheet.h                   |    6 +
 mr/f152.dir                       |    2 +-
 mr/f152.trr                       |   19 +-
 mr/f153.dir                       |    3 +
 mr/f153.trr                       |   14 +
 mr/mr0500.cpp                     |  788 ++++++++++++++++++++-
 mr/mr0500a.h                      |   74 +-
 mr/mr0500a.ini                    |   31 +
 mr/mr0500a.uml                    |  417 +++++++----
 mr/mr0500b.h                      |    5 +
 mr/mr0500b.uml                    |   41 ++
 mr/mr0500c.h                      |    4 +
 mr/mr0500c.uml                    |   49 ++
 mr/mr1100.cpp                     |  545 +++++++++------
 mr/mr1100a.frm                    |    4 +-
 mr/mr1100a.h                      |    3 +
 mr/mr1100a.uml                    |   38 +-
 mr/mr1100b.frm                    |   20 +-
 mr/mr2100.cpp                     |  264 +++++--
 mr/mr2100.h                       |    3 +
 mr/mr2100a.h                      |   10 +-
 mr/mr2100a.uml                    |   39 +-
 mr/mr2100b.uml                    |   19 +
 mr/mr2200.cpp                     |  509 +++++++++-----
 mr/mr2200.h                       |    4 -
 mr/mr2200a.h                      |    9 +-
 mr/mr2200a.uml                    |   56 +-
 mr/mr2201.cpp                     |   57 +-
 mr/mr2201.h                       |   28 +-
 mr/mr2202.cpp                     |    4 +
 mr/mrplib.cpp                     |  240 ++++++-
 mr/mrplib.h                       |   50 +-
 projects/agalib.dsp               |    6 +-
 projects/cg0.dsp                  | 1062 +++++++++++++++++++++++++++++
 projects/cg3.dsp                  |    2 +-
 projects/cg5.dsp                  |   27 +
 projects/li.dsw                   |   44 ++
 projects/li0.dsp                  |  463 +++++++++++++
 projects/{scp0.rc => li0.rc}      |    0
 projects/mr0.dsp                  |  316 +++++++++
 projects/mr1.dsp                  |   10 +-
 projects/{Scp0.dsp => pd1890.dsp} |   69 +-
 projects/pd1890.rc                |    4 +
 projects/pd6030.dsp               |  179 +++++
 projects/pd6030.rc                |    4 +
 projects/ps.dsw                   |   30 +
 projects/ve7.dsp                  |   97 +++
 projects/ve_masktab.dsp           |  316 ++-------
 sc/sc2600.cpp                     |   59 +-
 server/authoriz.cpp               |   18 +-
 ve/batbeld.h                      |    1 +
 ve/batbeld.uml                    |   19 +-
 ve/mainardi.ini                   |  286 ++++++++
 ve/opticpen.ini                   |    3 +
 ve/sconti.cpp                     |    4 +-
 ve/ve1300.alx                     |    7 +-
 ve/ve1300.cpp                     |   27 +-
 ve/ve2400.uml                     |    2 +-
 ve/ve6500.cpp                     |   88 ++-
 ve/ve6500.h                       |    1 +
 ve/ve6500.uml                     |    8 +-
 ve/ve65f734a.PWT                  |    1 +
 ve/ve65f734a.app                  |  344 ++++++++++
 ve/ve6f734a.ini                   |   15 +
 ve/ve7400.cpp                     |   74 +-
 ve/ve7400a.h                      |    2 -
 ve/ve7400a.uml                    |   39 +-
 ve/velib.h                        |    3 +-
 ve/velib02.cpp                    |   37 +-
 ve/velib03.cpp                    |   73 +-
 ve/velib04.h                      |    3 +
 ve/velib04a.cpp                   |   11 +-
 ve/velib04b.cpp                   |  115 ++--
 ve/velib04d.cpp                   |   68 +-
 ve/velib04e.cpp                   |  244 +++++--
 ve/velib04e.h                     |   26 +-
 ve/velib04e.uml                   |   52 +-
 ve/velib06.cpp                    |    7 +-
 ve/vetbdip.h                      |   45 ++
 ve/vetbdip.uml                    |  574 ++++++++++++++++
 xi/xi.h                           |    1 +
 xi/xistx.c                        |    8 +-
 xvaga/oswin32.cpp                 |    9 +-
 xvaga/xvaga.cpp                   |   32 +-
 137 files changed, 8471 insertions(+), 2990 deletions(-)
 create mode 100755 mr/f153.dir
 create mode 100755 mr/f153.trr
 create mode 100755 mr/mr0500a.ini
 create mode 100755 mr/mr0500b.h
 create mode 100755 mr/mr0500b.uml
 create mode 100755 mr/mr0500c.h
 create mode 100755 mr/mr0500c.uml
 create mode 100755 projects/li.dsw
 create mode 100755 projects/li0.dsp
 rename projects/{scp0.rc => li0.rc} (100%)
 rename projects/{Scp0.dsp => pd1890.dsp} (78%)
 create mode 100755 projects/pd1890.rc
 create mode 100755 projects/pd6030.dsp
 create mode 100755 projects/pd6030.rc
 create mode 100755 ve/mainardi.ini
 create mode 100755 ve/ve65f734a.PWT
 create mode 100755 ve/ve65f734a.app
 create mode 100755 ve/ve6f734a.ini
 create mode 100755 ve/vetbdip.h
 create mode 100755 ve/vetbdip.uml

diff --git a/ba/ba3100.cpp b/ba/ba3100.cpp
index 6c5cc3cb5..b12b28b7d 100755
--- a/ba/ba3100.cpp
+++ b/ba/ba3100.cpp
@@ -16,6 +16,7 @@
 #include "batbnot.h"
 
 #define REG_JOURNAL 5
+#define REG_DICHINT  10
 #define TAB_BANCHE      "%BAN"
 #define TAB_CAMBI       "CAM"
 #define TAB_DELEGHE     "%DEL"
@@ -32,6 +33,7 @@ class TGeneric_table_app : public TTable_application
   long       _oldditta;
   int        _oldanno;
   bool       _exist_journal;
+  bool       _exist_dich_int;
   bool       _stampa_intest;
 
   // ------------- specifiche tabella versamenti ed interessi IVA
@@ -64,6 +66,7 @@ protected:
 
 public:
   bool exist_journal() { return _exist_journal; }
+  bool exist_dich_int() { return _exist_dich_int; }
   char frequenza_versamenti(long firm, int year) const;
   
   TGeneric_table_app();
@@ -140,32 +143,33 @@ void TGeneric_table_app::init_insert_mode(TMask& m)
 
     m.set(F_STAMPA_INTESTAZIONE, _stampa_intest ? "X" : "");
 
-    if (ditta != _oldditta || anno != _oldanno)
-    {
-      _oldditta = ditta;
-      _oldanno = anno;
 
       TTable reg(TAB_REGISTRI);
       reg.put("CODTAB", m.get(F_ANNO));
 
       const TRectype to(reg.curr());
+
       _exist_journal = FALSE;
+      _exist_dich_int = FALSE;
 
       for (reg.read(_isgteq); !_exist_journal && reg.good() && reg.curr() <= to; reg.next())
         _exist_journal = (reg.get_long("I0") == REG_JOURNAL);
-    }  
-  } else
-  if (n == TAB_VERSAMENTI)
-  {
-    // Se il record e' nuovo prima carica il record precedente
-    load_rec_in_disabled_fields(m);
-    // poi copia il contenuto nei campi di input, come valori predefiniti
-    copy_rec_in_insert_fields(m);
-  } else
-  if (n == TAB_VALUTE)
-  {
-    m.enable(-3);
+			reg.zero();
+      reg.put("CODTAB", m.get(F_ANNO));
+      for (reg.read(_isgteq); !_exist_dich_int && reg.good() && reg.curr() <= to; reg.next())
+        _exist_dich_int = (reg.get_long("I0") == REG_DICHINT);
   }
+	else
+		if (n == TAB_VERSAMENTI)
+		{
+			// Se il record e' nuovo prima carica il record precedente
+			load_rec_in_disabled_fields(m);
+			// poi copia il contenuto nei campi di input, come valori predefiniti
+			copy_rec_in_insert_fields(m);
+		}
+		else
+		  if (n == TAB_VALUTE)
+				m.enable(-3);
 }
 
 void TGeneric_table_app::init_modify_mode(TMask& m) 
@@ -227,10 +231,13 @@ bool TGeneric_table_app::protected_record(TRectype& rec)
 
 HIDDEN bool tiporeg_handler(TMask_field& f, KEY k)
 {
-  if ((k == K_TAB || k == K_ENTER) && app().exist_journal() &&
-      (atoi(f.get()) == REG_JOURNAL)
-      )
+	const int tipo = atoi(f.get());
+  if ((k == K_TAB || k == K_ENTER) && app().exist_journal() && (tipo == REG_JOURNAL))
     return f.error_box(TR("Non e' possibile avere due registri giornale nello stesso anno"));
+  if ((k == K_TAB || k == K_ENTER) && app().exist_dich_int() && (tipo == REG_DICHINT))
+    return f.error_box(TR("Non e' possibile avere due registri dichiarazioni d'intenti nello stesso anno"));
+  if (k == K_SPACE)
+		f.mask().enable_page(1, tipo != REG_DICHINT);
   return TRUE;
 }
 
diff --git a/ba/ba3800.cpp b/ba/ba3800.cpp
index d0d60ae86..ac64895cc 100755
--- a/ba/ba3800.cpp
+++ b/ba/ba3800.cpp
@@ -1,5 +1,6 @@
 #include <mask.h>
 #include <printapp.h>
+#include <recarray.h>
 #include <tabutil.h>
 #include <utility.h>
 #include <sort.h>
@@ -16,36 +17,17 @@
 
 class BA3800_application : public TPrintapp
 {                              
-  struct bil_ivd
-  {
-    char   sez;
-    char   let;
-    char   numr[5];
-    char   num[4];
-    char   gruppo[4];
-    char   conto[4];
-    char   sottoc[8];
-  };
-  
-  bil_ivd*          _bil;
   TTable*           _tabivd;
-  TLocalisamfile*   _nditte;
-  TLocalisamfile*   _comuni;
-  TLocalisamfile*   _unloc;
-  TLocalisamfile*   _anag;
-  TLocalisamfile*   _pconti;
-  TLocalisamfile*   _clifo;  
-  TParagraph_string _descr;
   const char*       _buff;
   TSort*            _sort; 
   
   TDate   _datastampa;
   bool    _diffprod_fatto,_risimp_fatto;
-  TString _numr_tot,_num_tot,_numr,_numr_da_stamp,_num_da_stamp,_numr_stamp,_num_stamp;;
+  TString _numr_tot,_num_tot,_numr,_numr_da_stamp,_num_da_stamp,_numr_stamp,_num_stamp, _cont_num, _num;
   char    _sez_da_stamp,_let_da_stamp,_sez_stamp,_let_stamp,_sez_tot,_let_tot,_let,_sez;
-  int     _cont_let,_cont_numr,_cont_num,_cont_gcs,_num,_i;
+  int     _cont_let,_cont_numr,_cont_gcs,_i;
   bool    _reset_righe_stampa,_statopatr_no_stamp,_sbilancio_ordine; 
-  bool    _totale_attivita_gia_stampato,_totale_passivita_gia_stampato;    
+  bool    _totale_attivita_gia_stampato,_totale_passivita_gia_stampato, _vaccata;    
   bool    _sbilancio_patr_gia_stampato,_attivo_o_passivo;
   TString _causale_ap, _causale_chi, _totale;
   char _liv;
@@ -55,7 +37,7 @@ public:
 
   bool menu (MENU_TAG m) { return TPrintapp::menu(m) ; }
   virtual bool user_create() ;
-  virtual bool user_destroy();
+  virtual bool user_destroy() { delete _tabivd; return true;}
   virtual bool set_print(int);
   
   virtual bool preprocess_page  (int,int);
@@ -79,19 +61,19 @@ public:
   void init_sort();    
   void crea_sort_tabella();
   void crea_sort_piano_conti();
-  void scrivi_record(const TString&,const TString&,const TString&,int,int,int,long);
-  void riempi_record(const TString&,const TString&,const TString&,int,int,int,long);
-  void set_bil_key(bil_ivd* b, char sezione, char lettera,
-                   const char* numero_romano, int numero,
-                   bool conti_ordine = TRUE, int conto = 0,
+  void scrivi_record(const TString&,const TString&,const TString&, const TString &,int,int,long);
+  void riempi_record(const TString&,const TString&,const TString&, const TString &,int,int,long);
+  void set_bil_key(TString & key, char sezione, char lettera,
+                   const char* numero_romano, const char * numero,
+                   bool conti_ordine = true, int conto = 0,
                    int gruppo = 0, long sottoconto = 0L);
   const char* descrizione_lettera(char, char);
   const char* descrizione_numeroromano(char, char, int);
-  const char* descrizione_numero(char, char, int, int);
+  const char* descrizione_numero(char, char, int, const TString &);
   const char* descrizione_sottoconto(int, int, long);  
-  void setta_righe_descr(TParagraph_string&,const TString&,const TString&);
+  void setta_righe_descr(const char *, const char *);
   
-  BA3800_application(char livello) : _descr("", 40), _liv(toupper(livello)) {}
+  BA3800_application(char livello) : _liv(toupper(livello)) {}
 };
 
 void BA3800_application::postclose_print()
@@ -100,111 +82,73 @@ void BA3800_application::postclose_print()
     delete _sort;
 }
 
-void BA3800_application::set_bil_key(bil_ivd* b, char sezione, char lettera,
-                                     const char* numero_romano, int numero,
+void BA3800_application::set_bil_key(TString & key, char sezione, char lettera,
+                                     const char* numero_romano, const char * numero,
                                      bool conti_ordine, int gruppo, int conto,
                                      long sottoconto)
 
 {
-  b->sez = sezione;
-
   //Se esiste solamente la sezione,significa che e' un conto d'ordine
   //Forzo la lettera della classe a Z, per ottenere, grazie
   //all'ordinamento del sort, i record dei conti d'ordine per ultimi
+	if (sezione == '\0')
+		sezione = ' ';
+	if (lettera == '\0')
+		lettera = ' ';
+
+	key.format("%1c%1c%-4s%-4s", sezione, ((conti_ordine && lettera == '\0' && sezione < '3') ? 'Z' : lettera), numero_romano, numero);
 
-  b->let = (conti_ordine && lettera == '\0' && sezione < '3') ? 'Z' : lettera;
-  strcpy(b->numr, numero_romano);
-  sprintf(b->num , "%2d", numero);
   if (gruppo < 0)
-  {
-    strcpy(b->gruppo, "ZZZ");
-    strcpy(b->conto, "ZZZ");
-    strcpy(b->sottoc, "ZZZZZZ");
-  }
+    key << "ZZZZZZZZZZZZ";
   else
-    if (gruppo == 0)
-    {
-      strcpy(b->gruppo, "   ");
-      strcpy(b->conto, "   ");
-      strcpy(b->sottoc, "      ");
-    }
-    else
-    {
-      sprintf(b->gruppo , "%3d", gruppo);
-      sprintf(b->conto , "%3d", conto);
-      sprintf(b->sottoc , "%6ld", sottoconto);
-    }
+    key << format("%03d%03d%06ld", gruppo, conto, sottoconto);
 }
 
 void BA3800_application::scrivi_record(const TString& sez,
-                                       const TString& let,  const TString& numerorom,int numero,
+                                       const TString& let,  const TString& numerorom, const TString & numero,
                                        int g,int c,long s)
 {
   
   //Se esiste solamente la sezione,significa che e' un conto d'ordine
   //Forzo la lettera della classe a Z, per ottenere, grazie
   //all'ordinamento del sort, i record dei conti d'ordine per ultimi
+	TString key;
 
-  set_bil_key(_bil, sez[0], let[0], numerorom, numero, TRUE, g, c, s);
-  _sort->sort ((const char*) _bil);
+  set_bil_key(key, sez[0], let[0], numerorom, numero, true, g, c, s);
+  _sort->sort ((const char*) key);
 }
 
 void BA3800_application::riempi_record(const TString& sez,
-                                       const TString& let,  const TString& numerorom,int numero,
+                                       const TString& let,  const TString& numerorom, const TString & numero,
                                        int g,int c,long s)
 {
-  set_bil_key(_bil, sez[0], let[0], numerorom, numero, FALSE, g, c, s);
-  _sort->sort ((const char*) _bil);
+	TString key;
+
+  set_bil_key(key, sez[0], let[0], numerorom, numero, false, g, c, s);
+  _sort->sort ((const char*) key);
 }
 
 void BA3800_application::crea_sort_tabella()
 {
-  TRecnotype recno_prec=0l, recno_curr=0l;
-  TString codtab_prec;
   TTable tabivd(TAB_IVD);
-  TRecfield codtab_curr(tabivd.curr(),"CODTAB");
-  TRecfield sezione   (tabivd.curr(),"CODTAB",0,0);
-  TRecfield lettera   (tabivd.curr(),"CODTAB",1,1);
-  TRecfield numerorom (tabivd.curr(),"CODTAB",2,5);
-  TRecfield numero    (tabivd.curr(),"CODTAB",6,7);
-  int preclen;
-  bool FINITO=FALSE;
-  
-  tabivd.first();
-  codtab_prec = tabivd.get("CODTAB");
   
   // Compilo tanti record quante sono le classi IV direttiva trovate sulla
   // tabella %IVD, usando dei gruppi, conti e sottoconti fittizi. Successivamente
   // nel caso di stampa completa verranno stampati anche questi record; nel caso
   // di stampa non completa non verranno stampati.
   
-  do
+  for (int err = tabivd.first(); err == NOERR; err = tabivd.next())
   {
-    recno_prec  = tabivd.recno();
-    tabivd.next();
-    if (tabivd.eof())
-    {
-      tabivd.zero();
-      FINITO=TRUE;
-    }
-    recno_curr  = tabivd.recno();
-    preclen = codtab_prec.len();
-    if (!strncmp(codtab_curr,codtab_prec,preclen))
-      codtab_prec = (const char *)codtab_curr;
-    else
-    {
-      tabivd.readat(recno_prec);
-      const char sez = *((const char*) sezione);
-      const char let = *((const char*) lettera);
-      TString16  nrom((const char*)numerorom);
-      const int nu = (int) numero;
-      
-      set_bil_key(_bil, sez, let,(const char*)nrom, nu, FALSE,-1);
-      _sort->sort ((const char*) _bil);
-      tabivd.readat(recno_curr);
-      codtab_prec = (const char *)codtab_curr;
-    }
-  } while (!FINITO);
+		const TString & codtab = tabivd.get("CODTAB");
+    const char sez = codtab[0];
+    const char let = codtab[1];
+    const TString16 nrom(codtab.mid(2, 4));
+    const TString16 nu(codtab.mid(6));
+		TString key;
+    
+    set_bil_key(key, sez, let,(const char*)nrom, nu, false,-1);
+    _sort->sort ((const char*) key);
+  }
 }
 
 // Passo al sort tutti i record presenti su piano dei conti, aventi la classe
@@ -213,21 +157,17 @@ void BA3800_application::crea_sort_tabella()
 void BA3800_application::crea_sort_piano_conti()
 {
   TLocalisamfile pconti(LF_PCON);
-  TString sez,let,numerorom;
-  TString sez_conto,let_conto,numr_conto;
-  int     num_conto, indbil;
+  TString sez,let,numerorom, num_conto;
+  TString sez_conto,let_conto,numr_conto, numero;
+  int     indbil;
   char    sezione,lettera,tmcf;
-  int     numero,g,c;
+  int     g,c;
   long    s;
-  bool    classe_conto          = FALSE;
-  bool    conto_dettagliato     = FALSE;
+  bool    classe_conto          = false;
+  bool    conto_dettagliato     = false;
   bool    stsottbil;
-  c         = 0;
-  num_conto = 0;
-  tmcf      = ' ';
-  indbil    = 0;
 
-  for (pconti.first(); !pconti.eof(); pconti.next())
+  for (int err = pconti.first(); err == NOERR; err = pconti.next())
   {
     //    _prog->addstatus(1);
     g         = pconti.get_int (PCN_GRUPPO);
@@ -238,7 +178,9 @@ void BA3800_application::crea_sort_piano_conti()
     sezione   = sez[0];
     lettera   = let[0];
     numerorom = pconti.get(PCN_NUMRIVD);
-    numero    = pconti.get_int (PCN_NUMIVD);
+    numero    = pconti.get(PCN_NUMIVD);
+		if (atoi(numero) != 0 && numero.len() == 1)
+			numero.insert("0");  // pacco per fare andare anche i record vecchi cosa si deve fare!!!!
     
     // Se si tratta di un conto e contiene la classe, allora lo passo al sort.
     // Gli eventuali sottoconti avranno la stessa classe.
@@ -251,15 +193,15 @@ void BA3800_application::crea_sort_piano_conti()
 
       //Se sono nello stesso gruppo, ma ho un conto diverso da quello precedentemente
       //analizzato, e se questi contiene la classe IV dir. CEE,
-      //allore devo controllare se va dettagliato (se STSOTTBIL e' TRUE il conto non
-      //va dettagliato, se FALSE va dettagliato)
+      //allore devo controllare se va dettagliato (se STSOTTBIL e' true il conto non
+      //va dettagliato, se false va dettagliato)
 
       if (sez != "0")
       {
         if (stsottbil || tmcf == 'C' || tmcf == 'F')
-          conto_dettagliato = FALSE;
+          conto_dettagliato = false;
         else
-          conto_dettagliato = TRUE;
+          conto_dettagliato = true;
 
         sez_conto  = sez;
         
@@ -276,12 +218,12 @@ void BA3800_application::crea_sort_piano_conti()
         
         riempi_record(sez_conto,let_conto,numr_conto,num_conto,g,c,0);
         
-        classe_conto = TRUE;
+        classe_conto = true;
       }
       else
       {
-        classe_conto      = FALSE; // Metto conto dettagliato = TRUE perche' potrebbero esserci dei sottoconti
-        conto_dettagliato = TRUE;  // di questo conto che hanno la classe e quindi vanno stampati.
+        classe_conto      = false; // Metto conto dettagliato = true perche' potrebbero esserci dei sottoconti
+        conto_dettagliato = true;  // di questo conto che hanno la classe e quindi vanno stampati.
       }
     }
     
@@ -317,7 +259,7 @@ bool BA3800_application::set_print(int)
 
     _cont_let  = 0;
     _cont_numr = 0;
-    _cont_num  = 0;
+    _cont_num  = "";
     _cont_gcs  = 0;
     
     _totale = "XXXXXXXXXXX";
@@ -331,14 +273,15 @@ bool BA3800_application::set_print(int)
     _numr_tot   = "";
     _num_tot    = ""; 
     
-    _statopatr_no_stamp            = TRUE;   
-    _diffprod_fatto                = TRUE;            
-    _risimp_fatto                  = TRUE;
-    _totale_attivita_gia_stampato  = FALSE;
-    _totale_passivita_gia_stampato = FALSE;
-    _sbilancio_ordine              = FALSE; 
-    _sbilancio_patr_gia_stampato   = FALSE;
-    _attivo_o_passivo              = FALSE;
+    _statopatr_no_stamp            = true;   
+    _diffprod_fatto                = false;            
+    _risimp_fatto                  = false;
+    _totale_attivita_gia_stampato  = false;
+    _totale_passivita_gia_stampato = false;
+    _sbilancio_ordine              = false; 
+    _sbilancio_patr_gia_stampato   = false;
+    _attivo_o_passivo              = false;
+		_vaccata									  	 = false;
     
     printer().footerlen(5);
     
@@ -352,12 +295,11 @@ bool BA3800_application::set_print(int)
         crea_sort_piano_conti();
         _sort->endsort();
         intestazione_ditta();
-        delete _bil;
       }
     
-    return TRUE;
+    return true;
   }
-  return FALSE;
+  return false;
 }    
 
 void BA3800_application::totale_numero_arabo()
@@ -365,9 +307,9 @@ void BA3800_application::totale_numero_arabo()
   if (_cont_gcs != 0)//(_cont_gcs >= 2)
   {
     //Fai il totale del numero arabo e stampalo 
-    if (_num != 0)
+    if (_num.not_empty())
     {
-      set_row (_i,FR("@18gTotale@25g%2d@27g)"), _num);
+      set_row (_i,FR("@18gTotale@25g%-4s)"), (const char *) _num);
       set_row (_i++,"@86g%s", (const char*) _totale);
     }
   }
@@ -375,7 +317,7 @@ void BA3800_application::totale_numero_arabo()
 
 void BA3800_application::totale_numero_romano()
 {
-  if (_cont_num != 0)//(_cont_num >= 2)
+  if (_cont_num.not_empty())//(_cont_num >= 2)
   {
     //Fai il totale del numero romano e stampalo
     int numeror = atoi(_numr);
@@ -403,13 +345,10 @@ void BA3800_application::totale_lettera()
 
 void BA3800_application::stampa_totali_studio()
 {
-  TString16 diff_prod;
-  TString16 ris_imp;   
+  const TString16 diff_prod("9B");
+  const TString16 ris_imp  ("9E        21");
   
-  diff_prod.format("%c%c",'9','B');
-  ris_imp.format  ("%c%c%8s%2s",'9','E',"","21");
-  
-  _num  = atoi(_num_tot);
+  _num  = _num_tot;
   _numr = _numr_tot;
   _let  = _let_tot;
 
@@ -421,7 +360,7 @@ void BA3800_application::stampa_totali_studio()
     _sez_tot  = ' ';
   }    
 
-  if (_num_da_stamp!=_num_tot)
+  if (_num_da_stamp != _num_tot)
   {       
     totale_numero_arabo();
     
@@ -429,9 +368,10 @@ void BA3800_application::stampa_totali_studio()
     {
       TString16 classe;
       
-      classe.format("%c%c%8s%2s", _sez_da_stamp,_let_da_stamp,(const char*)_numr_da_stamp,(const char*)_num_da_stamp);
+      classe.format("%c%c%8s%-4s", _sez_da_stamp,_let_da_stamp,(const char*)_numr_da_stamp,(const char*)_num_da_stamp);
+			classe.rtrim();
       
-      if (classe > ris_imp && _risimp_fatto)
+      if (classe > ris_imp && !_risimp_fatto)
       { 
         if (_num_tot == "20" || _num_tot == "21")
         {
@@ -439,19 +379,19 @@ void BA3800_application::stampa_totali_studio()
           set_row (_i++,"@86g%s", (const char*) _totale);
           set_row (_i,FR("@4gRisultato prima delle imposte"));
           set_row (_i++,"@86g%s", (const char*) _totale);
-          _risimp_fatto = FALSE;
+          _risimp_fatto = true;
         }
       }
     }
     
     _cont_gcs = 0;
   }
-  if (_numr_da_stamp!=_numr_tot)
+  if (_numr_da_stamp != _numr_tot)
   {
     totale_numero_arabo();
     totale_numero_romano();
     _cont_gcs = 0;
-    _cont_num = 0;
+    _cont_num = "";
   }   
   if (_let_da_stamp!=_let_tot)
   { 
@@ -459,7 +399,8 @@ void BA3800_application::stampa_totali_studio()
     {
       TString16 classe;
       
-      classe.format("%c%c%8s%2s",_sez_stamp,_let_stamp,(const char*)_numr_stamp,(const char*)_num_stamp);
+      classe.format("%c%c%8s%-4s",_sez_stamp,_let_stamp,(const char*)_numr_stamp,(const char*)_num_stamp);
+			classe.rtrim();
       
       totale_numero_arabo();
       totale_numero_romano();
@@ -486,12 +427,12 @@ void BA3800_application::stampa_totali_studio()
         }
       }
       
-      if (classe > diff_prod && _diffprod_fatto)
+      if (classe > diff_prod && !_diffprod_fatto)
       { 
         if (_let_tot == 'A' || _let_tot == 'B') //Solo se esiste una delle due lettere
         {               
           set_row (_i++,FR("@4gDifferenza tra valore e costi della produzione@86g%s"), (const char*) _totale);
-          _diffprod_fatto = FALSE;
+          _diffprod_fatto = true;
         }
       }
     }
@@ -558,12 +499,12 @@ void BA3800_application::stampa_totali_studio()
     { 
       if (_tabivd->eof()) 
       {  
-        if ((_let_stamp == 'A' || _let_stamp == 'B') && _diffprod_fatto)//Solo se esiste una delle due lettere
+        if ((_let_stamp == 'A' || _let_stamp == 'B') && !_diffprod_fatto)//Solo se esiste una delle due lettere
         {               
           set_row (_i++, FR("@4gDifferenza tra valore e costi della produzione@86g%s"), (const char*) _totale);
-          _diffprod_fatto = FALSE;
+          _diffprod_fatto = true;
         }
-        if (_risimp_fatto)  
+        if (!_risimp_fatto)  
         {  
           set_row (_i, FR("@4gRisultato prima delle imposte"));
           set_row (_i++,"@86g%s", (const char*) _totale);
@@ -584,14 +525,11 @@ void BA3800_application::stampa_totali_studio()
 
 void BA3800_application::stampa_totali_ditta()
 {
-  bool gia_stampato_conto_ord = FALSE;
-  TString16 diff_prod;
-  TString16 ris_imp;   
+  bool gia_stampato_conto_ord = false;
+  const TString16 diff_prod("9B");
+  const TString16 ris_imp  ("9E        21");
   
-  diff_prod.format("%c%c",'9','B');
-  ris_imp.format  ("%c%c%8s%2s",'9','E',"","21");
-  
-  _num  = atoi(_num_tot);
+  _num  = _num_tot;
   _numr = _numr_tot;
   _let  = _let_tot;
 
@@ -604,9 +542,9 @@ void BA3800_application::stampa_totali_ditta()
   }  
   
   if ((_sez_stamp == '1' || _sez_stamp == '2') && _let_stamp != 'Z')  
-    _attivo_o_passivo = TRUE;
+    _attivo_o_passivo = true;
 
-  if (_num_da_stamp!=_num_tot)
+  if (_num_da_stamp != _num_tot)
   {       
     if (_let_stamp != 'Z')
     {
@@ -614,9 +552,9 @@ void BA3800_application::stampa_totali_ditta()
         if (_cont_gcs != 0)//(_cont_gcs >= 2)
         {
           //Fai il totale del numero arabo e stampalo 
-          if (_num != 0)
+          if (_num.not_empty())
           {
-            set_row (_i, FR("@18gTotale@25g%2d@27g)"), _num);
+            set_row (_i, FR("@18gTotale@25g%-4s)"), (const char *) _num);
             set_row (_i++,"@86g%s", (const char*) _totale);
           }
         }
@@ -625,9 +563,10 @@ void BA3800_application::stampa_totali_ditta()
     {
       TString16 classe;
       
-      classe.format("%c%c%8s%2s", _sez_da_stamp,_let_da_stamp,(const char*)_numr_da_stamp,(const char*)_num_da_stamp);
+      classe.format("%c%c%8s%-4s", _sez_da_stamp,_let_da_stamp,(const char*)_numr_da_stamp,(const char*)_num_da_stamp);
+			classe.rtrim();
       
-      if (classe > ris_imp && _risimp_fatto)
+      if (classe > ris_imp && !_risimp_fatto)
       { 
         if (_num_tot == "20" || _num_tot == "21")
         {
@@ -635,14 +574,14 @@ void BA3800_application::stampa_totali_ditta()
           set_row (_i++,"@86g%s", (const char*) _totale);
           set_row (_i, FR("@4gRisultato prima delle imposte"));
           set_row (_i++,"@86g%s", (const char*) _totale);
-          _risimp_fatto = FALSE;
+          _risimp_fatto = true;
         }
       }
     }
     
     _cont_gcs = 0;
   }
-  if (_numr_da_stamp!=_numr_tot)
+  if (_numr_da_stamp != _numr_tot)
   {
     if (_let_stamp != 'Z')
     {
@@ -651,13 +590,13 @@ void BA3800_application::stampa_totali_ditta()
         if (_cont_gcs != 0)//(_cont_gcs >= 2)
         {
           //Fai il totale del numero arabo e stampalo 
-          if (_num != 0)
+          if (_num.not_empty())
           {
-            set_row (_i, FR("@18gTotale@25g%2d@27g)"), _num);
+            set_row (_i, FR("@18gTotale@25g%-4s)"), (const char *) _num);
             set_row (_i++,"@86g%s", (const char*) _totale);
           }
         }
-        if (_cont_num != 0)//(_cont_num >= 2)
+        if (_cont_num.not_empty())//(_cont_num >= 2)
         {
           //Fai il totale del numero romano e stampalo
           int numeror = atoi(_numr);
@@ -679,18 +618,19 @@ void BA3800_application::stampa_totali_ditta()
     {
       TString16 classe;
       
-      classe.format("%c%c%8s%2s",_sez_stamp,_let_stamp,(const char*)_numr_stamp,(const char*)_num_stamp);
+      classe.format("%c%c%8s%-4s",_sez_stamp,_let_stamp,(const char*)_numr_stamp,(const char*)_num_stamp);
+			classe.ltrim();
       
       if (_cont_gcs != 0)//(_cont_gcs >= 2)
       {
         //Fai il totale del numero arabo e stampalo
-        if (_num != 0)
+        if (_num.not_empty())
         {
-          set_row (_i,FR("@18gTotale@25g%2d@27g)"), _num);
+          set_row (_i,FR("@18gTotale@25g%-4s)"), (const char *) _num);
           set_row (_i++,"@86g%s", (const char*) _totale);
         }
       }
-      if (_cont_num != 0)//(_cont_num >= 2)
+      if (_cont_num.not_empty())//(_cont_num >= 2)
       {
         //Fai il totale del numero romano e stampalo  
         int numeror = atoi(_numr);
@@ -728,7 +668,7 @@ void BA3800_application::stampa_totali_ditta()
         if (_let_tot == 'A' || _let_tot == 'B') //Solo se esiste una delle due lettere
         {               
           set_row (_i++, FR("@4gDifferenza tra valore e costi della produzione@86g%s"), (const char*)_totale);
-          _diffprod_fatto = FALSE;
+          _diffprod_fatto = false;
         }
       }
     }
@@ -741,13 +681,13 @@ void BA3800_application::stampa_totali_ditta()
           if (_cont_gcs != 0)//(_cont_gcs >= 2)
           {
             //Fai il totale del numero arabo e stampalo 
-            if (_num != 0)
+            if (_num.not_empty())
             {
-              set_row (_i,FR("@18gTotale@25g%2d@27g)"), _num);
+              set_row (_i,FR("@18gTotale@25g%-4s)"), (const char *) _num);
               set_row (_i++,"@86g%s", (const char*) _totale);
             }
           }
-          if (_cont_num != 0)//(_cont_num >= 2)
+          if (_cont_num.not_empty())//(_cont_num >= 2)
           {
             //Fai il totale del numero romano e stampalo
             int numeror = atoi(_numr);
@@ -776,7 +716,7 @@ void BA3800_application::stampa_totali_ditta()
         set_row (_i++,"@0g%c", app);
         set_row (_i,FR("@0gTOTALE ATTIVO"));
         set_row (_i++,"@86g%s", (const char*) _totale);
-        _totale_attivita_gia_stampato = TRUE;
+        _totale_attivita_gia_stampato = true;
       }
       
       if ((_sez_stamp == '2')&&(_let_da_stamp == 'Z'))
@@ -785,7 +725,7 @@ void BA3800_application::stampa_totali_ditta()
         set_row (_i++,"@0g%c", app);
         set_row (_i,FR("@0gTOTALE PASSIVO"));
         set_row (_i++,"@86g%s", (const char*) _totale);
-        _totale_passivita_gia_stampato = TRUE;
+        _totale_passivita_gia_stampato = true;
       }
       
       if ((_sez_stamp == '1')&&(_let_stamp == 'Z'))
@@ -794,7 +734,7 @@ void BA3800_application::stampa_totali_ditta()
         set_row (_i++,"@0g%c", app);
         set_row (_i, FR("@0gTOTALE CONTI D' ORDINE ATTIVI"));
         set_row (_i++,"@86g%s", (const char*) _totale);
-        gia_stampato_conto_ord = TRUE;
+        gia_stampato_conto_ord = true;
       }
       
       if ((_sez_stamp == '2')&&(_let_stamp == 'Z'))
@@ -804,14 +744,14 @@ void BA3800_application::stampa_totali_ditta()
         set_row (_i, FR("@0gTOTALE CONTI D' ORDINE PASSIVI"));
         set_row (_i++,"@86g%s", (const char*) _totale);
         _i++;                                            
-        gia_stampato_conto_ord = TRUE;
+        gia_stampato_conto_ord = true;
         if (!_attivo_o_passivo) 
         {
           set_row (_i++,FR("@0gSALDO CONTI D' ORDINE"));
           set_row (_i,FR("@0gSBILANCIO"));
           set_row (_i++,"@86g%s", (const char*) _totale);
-          _sbilancio_ordine = TRUE;  
-          _sbilancio_patr_gia_stampato = TRUE;
+          _sbilancio_ordine = true;  
+          _sbilancio_patr_gia_stampato = true;
         }
       }
     }
@@ -828,13 +768,13 @@ void BA3800_application::stampa_totali_ditta()
         if (_cont_gcs != 0)//(_cont_gcs >= 2)
         {
           //Fai il totale del numero arabo e stampalo
-          if (_num != 0)
+          if (_num .not_empty())
           {
-            set_row (_i,FR("@18gTotale@25g%2d@27g)"), _num);
+            set_row (_i,FR("@18gTotale@25g%-4s)"), (const char *) _num);
             set_row (_i++,"@86g%s", (const char*) _totale);
           }
         }
-        if (_cont_num != 0)//(_cont_num >= 2)
+        if (_cont_num .not_empty())//(_cont_num >= 2)
         {
           //Fai il totale del numero romano e stampalo
           int numeror = atoi(_numr);
@@ -895,7 +835,7 @@ void BA3800_application::stampa_totali_ditta()
           set_row (_i++, FR("@0gSALDO STATO PATRIMONIALE"));
           set_row (_i, FR("@0gSBILANCIO (ATTIVO - PASSIVO)"));
           set_row (_i++,"@86g%s", (const char*) _totale);
-          _sbilancio_patr_gia_stampato = TRUE;
+          _sbilancio_patr_gia_stampato = true;
         }
       }
       if ((_sez_stamp == '1')&&(_let_stamp == 'Z'))
@@ -919,7 +859,7 @@ void BA3800_application::stampa_totali_ditta()
           set_row (_i++, FR("@0gSALDO CONTI D' ORDINE"));
           set_row (_i, FR("@0gSBILANCIO"));
           set_row (_i++,"@86g%s", (const char*) _totale);   
-          _sbilancio_ordine = TRUE;  
+          _sbilancio_ordine = true;  
         }
       }
     }
@@ -956,9 +896,9 @@ void BA3800_application::stampa_totali_ditta()
         if ((_let_stamp == 'A' || _let_stamp == 'B') && _diffprod_fatto)//Solo se esiste una delle due lettere
         {               
           set_row (_i++,FR("@4gDifferenza tra valore e costi della produzione@86g%s"), (const char*) _totale);
-          _diffprod_fatto = FALSE;
+          _diffprod_fatto = false;
         }
-        if (_risimp_fatto)  
+        if (!_risimp_fatto)  
         {  
           set_row (_i, FR("@4gRisultato prima delle imposte"));
           set_row (_i++,"@86g%s", (const char*) _totale);
@@ -971,7 +911,7 @@ void BA3800_application::stampa_totali_ditta()
       set_row (_i++,"@86g%s", (const char*) _totale);
     }
     _cont_gcs = 0;
-    _cont_num = 0;
+    _cont_num = "";
     _cont_numr = 0;
     _cont_let = 0;
   }
@@ -988,11 +928,11 @@ print_action BA3800_application::postprocess_page(int file, int counter)
         reset_print();
         _i = 1;
         setta_righe_studio(TR("CONTO ECONOMICO"));
-        _reset_righe_stampa = FALSE; 
+        _reset_righe_stampa = false; 
       }
     }
 
-    set_auto_ff(FALSE);   
+    set_auto_ff(false);   
     
     if (_tabivd->eof()) 
       return NEXT_PAGE;
@@ -1011,18 +951,18 @@ print_action BA3800_application::postprocess_page(int file, int counter)
           reset_print();
           _i = 1;
           setta_righe_ditta(TR("CONTI D' ORDINE"));
-          _reset_righe_stampa = FALSE;
+          _reset_righe_stampa = false;
         }
         if (_sez_da_stamp == '9')
         {                      
           reset_print();
           _i = 1;
           setta_righe_ditta(TR("CONTO ECONOMICO"));
-          _reset_righe_stampa = FALSE; 
+          _reset_righe_stampa = false; 
         }
       }
 
-      set_auto_ff(FALSE); 
+      set_auto_ff(false); 
       
       if (_buff == NULL)
         return NEXT_PAGE;
@@ -1036,19 +976,19 @@ bool BA3800_application::preprocess_page(int file, int counter)
   if (_liv == 'S')
   {
     if (preprocess_studio(counter))
-      return TRUE;
+      return true;
     else 
-      return FALSE;
+      return false;
   }
   else if (_liv == 'D')
   {
     if (preprocess_ditta(counter))
-      return TRUE;
+      return true;
     else 
-      return FALSE;
+      return false;
   }
 
-  return TRUE;
+  return true;
 }
 
 
@@ -1073,7 +1013,7 @@ bool BA3800_application::preprocess_studio(int counter)
     _i = 1;
   }
   else
-    _reset_righe_stampa = TRUE;                 
+    _reset_righe_stampa = true;                 
   
   if (counter)
   {
@@ -1087,40 +1027,34 @@ bool BA3800_application::preprocess_studio(int counter)
     _num_tot    = _num_da_stamp;
   }
 
-  if (_tabivd->eof()) 
-  {
-    stampa_totali_studio(); 
-    _sez_da_stamp = ' ';
-    _sez_stamp    = ' ';
-    return TRUE;
-  }      
 
   if (!_tabivd->eof())
   { 
     TString16 codtab;
 
-    //    _classe_da_stampare = format ("%1c%1c%8s%2d",bil->sez,bil->let,(const char*) bil->numr,bil->num);
-    
     codtab = _tabivd->get("CODTAB");
     _sez_da_stamp  = codtab[0];
     _let_da_stamp  = codtab[1];
-    _numr_da_stamp = codtab.mid(2,4);
+    _numr_da_stamp = codtab.mid(2, 4);
     _numr_da_stamp.ltrim();
-    _num_da_stamp  = codtab.mid(6,2);
+    _num_da_stamp  = codtab.mid(6, 4);
     _num_da_stamp.ltrim();
 
     if (counter)
       stampa_totali_studio(); 
-
-    return TRUE;
   }
   else
-    return FALSE;  
+	{
+		stampa_totali_studio(); 
+		_sez_da_stamp = ' ';
+		_sez_stamp    = ' ';
+	}      
+  return true;
 }
 
 bool BA3800_application::preprocess_ditta(int counter)
 {
-  struct bil_ivd* bil = (struct bil_ivd*) _buff;
+  TString  key((const char*)_buff);
   int     g,c;
   long    s;
   
@@ -1136,54 +1070,48 @@ bool BA3800_application::preprocess_ditta(int counter)
     _i = 1;
   }
   else
-    _reset_righe_stampa = TRUE;
+    _reset_righe_stampa = true;
   
   if (counter)
   {
-    _sez_stamp  = bil->sez;
-    _let_stamp  = bil->let;
-    _numr_stamp = bil->numr;
+    _sez_stamp = key[0];
+    _let_stamp = key[1];
+    _numr_stamp = key.mid(2, 4);
     _numr_stamp.ltrim();
-    _num_stamp  = bil->num;
+    _num_stamp = key.mid(6, 4);
     _num_stamp.ltrim();
-    _sez_tot  = bil->sez;
-    _let_tot  = bil->let;
-    _numr_tot = bil->numr;
-    _numr_tot.ltrim();
-    _num_tot  = bil->num;
-    _num_tot.ltrim();
+    _sez_tot = _sez_stamp;
+    _let_tot = _let_stamp;
+    _numr_tot = _numr_stamp;
+    _num_tot = _num_stamp;
   }
 
   _buff = _sort->retrieve();
 
-  if (_buff == NULL) 
+  if (_buff != NULL)
+  {
+		key = (const char *) _buff;
+    _sez_da_stamp  = key[0];
+    _let_da_stamp  = key[1];
+    _numr_da_stamp = key.mid(2, 4);
+    _numr_da_stamp.ltrim();
+    _num_da_stamp  = key.mid(6, 4);
+    _num_da_stamp.ltrim();
+    g = atoi(key.mid(10, 3));
+    c = atoi(key.mid(13, 3));
+    s = atol(key.mid(16));      
+
+    if (counter)
+      stampa_totali_ditta(); 
+  }
+  else
   {
     stampa_totali_ditta(); 
     _sez_da_stamp = ' ';
     _sez_stamp    = ' ';
-    return TRUE;
-  }      
+	}
 
-  if (_buff != NULL)
-  {
-    bil = (struct bil_ivd*) _buff;
-    _sez_da_stamp  = bil->sez;
-    _let_da_stamp  = bil->let;
-    _numr_da_stamp = bil->numr;
-    _numr_da_stamp.ltrim();
-    _num_da_stamp  = bil->num;
-    _num_da_stamp.ltrim();
-    g = atoi(bil->gruppo);
-    c = atoi(bil->conto);
-    s = atol(bil->sottoc);      
-
-    if (counter)
-      stampa_totali_ditta(); 
-
-    return TRUE;
-  }
-  else
-    return FALSE;  
+  return true;
 }
 
 void BA3800_application::set_page(int file, int counter)
@@ -1195,12 +1123,12 @@ void BA3800_application::set_page(int file, int counter)
       if ((_sez_da_stamp=='1')||((_sez_da_stamp=='2')&&(_statopatr_no_stamp)))
       {
         setta_righe_studio(TR("STATO PATRIMONIALE"));
-        _statopatr_no_stamp = FALSE;
+        _statopatr_no_stamp = false;
       }
       if (_sez_da_stamp == '2')
         setta_righe_studio("");
       if (_sez_da_stamp == '9')
-        set_auto_ff(TRUE);
+        set_auto_ff(true);
     }
     else 
     {
@@ -1215,12 +1143,12 @@ void BA3800_application::set_page(int file, int counter)
       if ((_sez_da_stamp=='1')||((_sez_da_stamp=='2')&&(_statopatr_no_stamp)))
       {
         setta_righe_ditta (TR("STATO PATRIMONIALE"));
-        _statopatr_no_stamp = FALSE;
+        _statopatr_no_stamp = false;
       }
       if (_sez_da_stamp == '2')
         setta_righe_ditta("");
       if ((_sez_da_stamp == '5') || (_sez_da_stamp == '9'))
-        set_auto_ff(TRUE);
+        set_auto_ff(true);
     }
     else
     {
@@ -1232,24 +1160,13 @@ void BA3800_application::set_page(int file, int counter)
 
 void BA3800_application::setta_righe_studio(const char * titolo)
 {
-  int numeror, numero;
-  TString numrom;
-  TString descr_let,descr_numr,descr_num;
-  bool stampa_classe = TRUE; 
-  TString lettera  = "@1g)@3g%s";
-  TString lettera2 = "@3g%s";
-  TString numr     = "@12g-@14g%s"; 
-  TString numr2    = "@14g%s";
-  TString num      = "@15g)@18g%s"; 
-  TString num2     = "@18g%s";
+  int numeror;
+  TString numrom, numero;
+  bool stampa_classe = true; 
   numeror = atoi(_numr_da_stamp);
   numrom  = itor(numeror);
-  numero  = atoi(_num_da_stamp);  
-  
-
-  descr_let  = descrizione_lettera(_sez_da_stamp,_let_da_stamp);
-  descr_numr = descrizione_numeroromano(_sez_da_stamp,_let_da_stamp,numeror);
-  descr_num  = descrizione_numero(_sez_da_stamp,_let_da_stamp,numeror,numero);
+  numero  = _num_da_stamp;  
+	numero.ltrim();
 
   //Se la classe prelevata dal record corrente del sort e' diversa dalla classe
   //prelevata dal record precedente, allora stampo la nuova classe con i relativi
@@ -1283,99 +1200,97 @@ void BA3800_application::setta_righe_studio(const char * titolo)
       { 
         _cont_let  = 1;
         _cont_numr = 1;
-        _cont_num  = 1;
+        _cont_num  = "1";
         _cont_gcs  = 1;
 
         if (_let_da_stamp != ' ')
         {                                                 
-          set_row(_i,"@0g%c", _let_da_stamp);  
-          _descr = (const char*) descr_let;   
-          setta_righe_descr(_descr,lettera,lettera2);
-          //          set_row(_i++,"@1g)@3g%s", (const char*) descr_let);
+          set_row(_i,"@0g%c)", _let_da_stamp);  
+					const TString & descr = descrizione_lettera(_sez_da_stamp,_let_da_stamp);
+          setta_righe_descr(descr, "@3g%s");
         }
         if (numrom != "")
         {                    
-          set_row(_i,"@3g%8s", (const char*) numrom);
-          _descr = (const char*) descr_numr;
-          setta_righe_descr(_descr,numr,numr2);
-          //          set_row(_i++,"@12g-@14g%s", (const char*) descr_numr);
+          set_row(_i,"@3g%8s -", (const char*) numrom);
+					const TString & descr = descrizione_numeroromano(_sez_da_stamp,_let_da_stamp,numeror);
+          setta_righe_descr(descr, "@14g%s");
         }
-        if (numero != 0)
+        if (numero.not_empty())
         {  
-          set_row(_i,"@13g%s", (const char*) _num_da_stamp);
-          _descr = (const char*) descr_num;
-          setta_righe_descr(_descr,num,num2);
-          //          set_row(_i++,"@15g)@18g%s", (const char*) descr_num);
+          set_row(_i,"@13g%-4s)", (const char*) _num_da_stamp);
+				  const TString & descr = descrizione_numero(_sez_da_stamp,_let_da_stamp,numeror,numero);
+          setta_righe_descr(descr,"@20g%s");
         }
       }
     }
   }
   else
-    if ((_let_da_stamp!=_let_stamp)&&(_sez_da_stamp==_sez_stamp))
+    if ((_let_da_stamp != _let_stamp) && (_sez_da_stamp == _sez_stamp))
     {
       if (stampa_classe)
       {
-        if ((_sez_da_stamp=='1')||(_sez_da_stamp=='2')||(_sez_da_stamp=='9'))
+        if ((_sez_da_stamp=='1') ||
+					  (_sez_da_stamp=='2') || 
+						(_sez_da_stamp=='9'))
         {                                                        
           _cont_numr = 1;
-          _cont_num  = 1;
+          _cont_num  = "1";
           _cont_gcs  = 1;
           if (_let_da_stamp != ' ')
           {                                                 
-            set_row(_i,"@0g%c", _let_da_stamp);
-            _descr = (const char*) descr_let;   
-            setta_righe_descr(_descr,lettera,lettera2);
-            // set_row(_i++,"@1g)@3g%s", (const char*) descr_let);
+            set_row(_i,"@0g%c)", _let_da_stamp);
+						const TString & descr = descrizione_lettera(_sez_da_stamp,_let_da_stamp);
+            setta_righe_descr(descr, "@3g%s");
           }
           if (numrom != "")
           {                               
-            set_row(_i,"@3g%8s", (const char*) numrom);
-            _descr = (const char*) descr_numr;
-            setta_righe_descr(_descr,numr,numr2);
-            //set_row(_i++,"@12g-@14g%s", (const char*) descr_numr);
+            set_row(_i,"@3g%8s -", (const char*) numrom);
+						const TString & descr = descrizione_numeroromano(_sez_da_stamp,_let_da_stamp,numeror);
+            setta_righe_descr(descr, "@14g%s");
           }
-          if (numero != 0)
+          if (numero.not_empty())
           {  
-            set_row(_i,"@13g%s", (const char*) _num_da_stamp);
-            _descr = (const char*) descr_num;
-            setta_righe_descr(_descr,num,num2);
-            //set_row(_i++,"@15g)@18g%s", (const char*) descr_num); 
+            set_row(_i,"@13g%-4s)", (const char*) _num_da_stamp);
+					  const TString & descr = descrizione_numero(_sez_da_stamp,_let_da_stamp,numeror,numero);
+            setta_righe_descr(descr, "@20g%s");
           }
         }
       }
     }
     else
-      if ((_numr_da_stamp!=_numr_stamp)&&(_sez_da_stamp==_sez_stamp)&&(_let_da_stamp==_let_stamp))
+      if ((_numr_da_stamp != _numr_stamp) &&
+				  (_sez_da_stamp == _sez_stamp) &&
+					(_let_da_stamp == _let_stamp))
       {
         if ((_sez_da_stamp=='1')||(_sez_da_stamp=='2')||(_sez_da_stamp=='9'))
         { 
-          _cont_num  = 1;
+          _cont_num  = "1";
           _cont_gcs  = 1;
           if (numrom != "")
           {                               
-            set_row(_i,"@3g%8s", (const char*) numrom);
-            _descr = (const char*) descr_numr;
-            setta_righe_descr(_descr,numr,numr2);
-            //set_row(_i++,"@12g-@14g%s", (const char*) descr_numr);
+            set_row(_i,"@3g%8s -", (const char*) numrom);
+						const TString & descr = descrizione_numeroromano(_sez_da_stamp,_let_da_stamp,numeror);
+            setta_righe_descr(descr, "@14g%s");
           }
-          if (numero != 0)
+          if (numero.not_empty())
           {   
-            set_row(_i,"@13g%s", (const char*) _num_da_stamp);
-            _descr = (const char*) descr_num;
-            setta_righe_descr(_descr,num,num2);
-            //set_row(_i++,"@15g)@18g%s", (const char*) descr_num);
+            set_row(_i,"@13g%-4s)", (const char*) _num_da_stamp);
+					  const TString & descr = descrizione_numero(_sez_da_stamp,_let_da_stamp,numeror,numero);
+            setta_righe_descr(descr, "@20g%s");
           }
         }
       }
       else
-        if ((_num_da_stamp!=_num_stamp)&&(_sez_da_stamp==_sez_stamp)&&(_let_da_stamp==_let_stamp)&&(_numr_da_stamp==_numr_stamp))
+        if ((_num_da_stamp != _num_stamp) && 
+					  (_sez_da_stamp == _sez_stamp) &&
+						(_let_da_stamp == _let_stamp) &&
+						(_numr_da_stamp==_numr_stamp))
         {
           if ((_sez_da_stamp=='1')||(_sez_da_stamp=='2')||(_sez_da_stamp=='9'))
           {   
-            set_row(_i,"@13g%s", (const char*) _num_da_stamp);
-            _descr = (const char*) descr_num;
-            setta_righe_descr(_descr,num,num2);
-            //set_row(_i++,"@15g)@18g%s", (const char*) descr_num);
+            set_row(_i,"@13g%-4s)", (const char*) _num_da_stamp);
+					  const TString & descr = descrizione_numero(_sez_da_stamp,_let_da_stamp,numeror,numero);
+            setta_righe_descr(descr, "@20g%s");
             _cont_gcs = 1;
           }
         }
@@ -1383,40 +1298,35 @@ void BA3800_application::setta_righe_studio(const char * titolo)
 
 void BA3800_application::setta_righe_ditta(const char* titolo)
 {
-  struct bil_ivd* bil = (struct bil_ivd*) _buff;
-  int numeror, numero, gruppo, conto;
+  TString key((const char *) _buff);
+  int gruppo, conto;
   char sezione,lettera;
   long sottoc;
-  TString numrom,numr;
-  TString descr_let,descr_numr,descr_num,descr_sottoc,descr_classe;
-  bool stampa_classe = TRUE;    
-  TString lettera1  = "@1g)@3g%s";
-  TString lettera2 = "@3g%s";
-  TString numr1     = "@12g-@14g%s"; 
-  TString numr2    = "@14g%s";
-  TString num      = "@15g)@18g%s"; 
-  TString num2     = "@18g%s";
+  TString numrom, numero, numr;
+  bool stampa_classe = true;    
   
-  sezione = bil->sez;
-  lettera = bil->let;
-  numr = bil->numr;
-  //  numr.ltrim();
-  numeror = atoi(bil->numr);
-  numrom  = itor(numeror);
-  numero  = atoi(bil->num);
-  //  num     = bil->num;
-  gruppo  = atoi(bil->gruppo);
-  conto   = atoi(bil->conto);
-  sottoc  = atoi(bil->sottoc);
-  descr_let  = descrizione_lettera(sezione,lettera);
-  descr_numr = descrizione_numeroromano(sezione,lettera,numeror);
-  descr_num  = descrizione_numero(sezione,lettera,numeror,numero);
-  descr_sottoc = descrizione_sottoconto(gruppo,conto,sottoc);
+  sezione = key[0];
+  lettera = key[1];
+  numr = key.mid(2, 4);
+  numr.ltrim();
+	numrom = itor(atoi(numr));
+  numero =  key.mid(6, 4);
+  numero.ltrim();
+  gruppo = atoi(key.mid(10, 3));
+  conto = atoi(key.mid(13, 3));
+  sottoc  = atol(key.mid(16));      
 
   //Se la classe prelevata dal record corrente del sort e' diversa dalla classe
   //prelevata dal record precedente, allora stampo la nuova classe con i relativi
   //sottoconti. In caso contrario continuo a stampare solo i sottoconti.
 
+  if (sezione == '1' && lettera == 'A' && !_vaccata)
+	{
+    set_row (_i, FR("@3gTotale  )"));
+    set_row (_i++,"@86g%s", (const char*) _totale);
+		_vaccata = true;
+	}
+
   if (_sez_da_stamp != _sez_stamp)
   {
     set_row (_i++,"@0g%s", titolo);
@@ -1429,7 +1339,7 @@ void BA3800_application::setta_righe_ditta(const char* titolo)
       set_row (_i++,"@0g%c", app);   
       set_row (_i++,FR("@0gCONTI D' ORDINE ATTIVI"));
       set_row (_i++,"@0g%c", app);
-      stampa_classe = FALSE;
+      stampa_classe = false;
     } 
     else
       if ((_sez_da_stamp == '1')&&(_let_da_stamp != 'Z'))
@@ -1446,7 +1356,7 @@ void BA3800_application::setta_righe_ditta(const char* titolo)
       set_row(_i++,"@0g%c", app); 
       set_row (_i++, FR("@0gCONTI D' ORDINE PASSIVI"));
       set_row(_i++,"@0g%c", app); 
-      stampa_classe = FALSE;
+      stampa_classe = false;
     } 
     else
       if ((_sez_da_stamp == '2')&&(_let_da_stamp != 'Z'))
@@ -1461,46 +1371,46 @@ void BA3800_application::setta_righe_ditta(const char* titolo)
     {
       if ((_sez_da_stamp=='1')||(_sez_da_stamp=='2')||(_sez_da_stamp== '9'))
       { 
-        //set_row(_i++,"@0g%s", (const char*) _descr_sez);  
         _cont_let  = 1;
         _cont_numr = 1;
-        _cont_num  = 1;
+        _cont_num  = "1";
         _cont_gcs  = 1;
 
         if (lettera != ' ')
         {
-          set_row(_i,"@0g%c", bil->let); 
-          _descr = (const char*) descr_let;   
-          setta_righe_descr(_descr,lettera1,lettera2);
-          //set_row(_i++,"@1g)@3g%s", (const char*) descr_let);
+					const TString descr(descrizione_lettera(sezione, lettera));
+
+          set_row(_i,"@0g%c)", lettera); 
+          setta_righe_descr(descr, "@3g%s");
         }
         if (numrom != "")
         {
-          set_row(_i,"@3g%8s", (const char*) numrom);
-          _descr = (const char*) descr_numr;
-          setta_righe_descr(_descr,numr1,numr2);
-          //set_row(_i++,"@12g-@14g%s", (const char*) descr_numr);
+          set_row(_i,"@3g%8s -", (const char*) numrom);
+				  const TString & descr = descrizione_numeroromano(sezione, lettera, atoi(numr));
+          setta_righe_descr(descr, "@14g%s");
+ 
         }
-        if (numero != 0)
+        if (numero.not_empty())
         {
-          set_row(_i,"@13g%s", bil->num);
-          _descr = (const char*) descr_num;
-          setta_righe_descr(_descr,num,num2);
-          //set_row(_i++,"@15g)@18g%s", (const char*) descr_num);
+          set_row(_i,"@13g%-4s)", (const char *) numero);
+				  const TString & descr = descrizione_numero(sezione, lettera, atoi(numr), numero);
+          setta_righe_descr(descr, "@20g%s");
         }
       }
     }
   }
   else
-    if ((_let_da_stamp!=_let_stamp)&&(_sez_da_stamp==_sez_stamp))
+    if ((_let_da_stamp != _let_stamp) &&
+			  (_sez_da_stamp == _sez_stamp))
     {
-      if ((_sez_da_stamp == '1')&&(_let_da_stamp == 'Z'))
+      if ((_sez_da_stamp == '1') &&
+				  (_let_da_stamp == 'Z'))
       {
         char app = ' ';
         set_row (_i++,"@0g%c", app);   
         set_row (_i++,FR("@0gCONTI D' ORDINE ATTIVI"));
         set_row (_i++,"@0g%c", app);
-        stampa_classe = FALSE;
+        stampa_classe = false;
       }
       if ((_sez_da_stamp == '2')&&(_let_da_stamp == 'Z'))
       {
@@ -1508,102 +1418,92 @@ void BA3800_application::setta_righe_ditta(const char* titolo)
         set_row(_i++,"@0g%c", app); 
         set_row (_i++,FR("@0gCONTI D' ORDINE PASSIVI"));
         set_row(_i++,"@0g%c", app); 
-        stampa_classe = FALSE;
+        stampa_classe = false;
       }
       if (stampa_classe)
       {
         if ((_sez_da_stamp=='1')||(_sez_da_stamp=='2')||(_sez_da_stamp=='9'))
         {
-          set_row(_i,"@0g%c", bil->let);  
-          _descr = (const char*) descr_let;   
-          setta_righe_descr(_descr,lettera1,lettera2);
-          //set_row(_i++,"@1g)@3g%s", (const char*) descr_let);
-          //_cont_let += 1;
+          set_row(_i,"@0g%c)", lettera);  
+					const TString descr(descrizione_lettera(sezione, lettera));
+          setta_righe_descr(descr, "@3g%s");
           _cont_numr = 1;
-          _cont_num  = 1;
+          _cont_num  = "1";
           _cont_gcs  = 1;
           
           if (numrom != "")
           {
-            set_row(_i,"@3g%8s", (const char*) numrom);
-            _descr = (const char*) descr_numr;
-            setta_righe_descr(_descr,numr1,numr2);
-            //set_row(_i++,"@12g-@14g%s", (const char*) descr_numr);
+            set_row(_i,"@3g%8s -", (const char*) numrom);
+					  const TString & descr = descrizione_numeroromano(sezione, lettera, atoi(numr));
+            setta_righe_descr(descr, "@14g%s");
           }
-          if (numero != 0)
+          if (numero.not_empty())
           {
-            set_row(_i,"@13g%s", bil->num);
-            _descr = (const char*) descr_num;
-            setta_righe_descr(_descr,num,num2);
-            //set_row(_i++,"@15g)@18g%s", (const char*) descr_num); 
+            set_row(_i,"@13g%-4s)", (const char *) numero);
+						const TString & descr = descrizione_numero(sezione, lettera, atoi(numr), numero);
+            setta_righe_descr(descr, "@20g%s");
           }
         }
       }
     }
     else
-      if ((_numr_da_stamp!=_numr_stamp)&&(_sez_da_stamp==_sez_stamp)&&(_let_da_stamp==_let_stamp))
+      if ((_numr_da_stamp != _numr_stamp) &&
+				  (_sez_da_stamp == _sez_stamp) &&
+					(_let_da_stamp==_let_stamp))
       {
         if ((_sez_da_stamp=='1')||(_sez_da_stamp=='2')||(_sez_da_stamp=='9'))
         {
-          set_row(_i,"@3g%8s", (const char*) numrom);
-          _descr = (const char*) descr_numr;
-          setta_righe_descr(_descr,numr1,numr2);
-          //set_row(_i++,"@12g-@14g%s", (const char*) descr_numr);
-          //_cont_numr += 1; 
-          //_cont_numr = 1; 
-          _cont_num  = 1;
+          set_row(_i,"@3g%8s -", (const char*) numrom);
+				  const TString & descr = descrizione_numeroromano(sezione, lettera, atoi(numr));
+          setta_righe_descr(descr, "@14g%s");
+          _cont_num  = "1";
           _cont_gcs  = 1;
           
-          if (numero != 0)
+          if (numero.not_empty())
           {
-            set_row(_i,"@13g%s", bil->num);
-            _descr = (const char*) descr_num;
-            setta_righe_descr(_descr,num,num2);
-            //set_row(_i++,"@15g)@18g%s", (const char*) descr_num);
+            set_row(_i,"@13g%-4s)", (const char *) numero);
+						const TString & descr = descrizione_numero(sezione, lettera, atoi(numr), numero);
+            setta_righe_descr(descr, "@20g%s");
           }
         }
       }
       else
-        if ((_num_da_stamp!=_num_stamp)&&(_sez_da_stamp==_sez_stamp)&&(_let_da_stamp==_let_stamp)&&(_numr_da_stamp==_numr_stamp))
+        if ((_num_da_stamp != _num_stamp) &&
+					  (_sez_da_stamp == _sez_stamp) &&
+						(_let_da_stamp == _let_stamp) &&
+						(_numr_da_stamp == _numr_stamp))
         {
-          if ((_sez_da_stamp=='1')||(_sez_da_stamp=='2')||(_sez_da_stamp=='9'))
+          if ((_sez_da_stamp == '1') ||
+						  (_sez_da_stamp == '2') ||
+							(_sez_da_stamp == '9'))
           {
-            set_row(_i,"@13g%s", bil->num);
-            _descr = (const char*) descr_num;
-            setta_righe_descr(_descr,num,num2);
-            //set_row(_i++,"@15g)@18g%s", (const char*) descr_num);
-            //_cont_num += 1;   
+            set_row(_i,"@13g%-4s)", (const char *) numero);
+						const TString & descr = descrizione_numero(sezione, lettera, atoi(numr), numero);
+            setta_righe_descr(descr, "@20g%s");
             _cont_gcs = 1;
           }
         }
-  if (bil->gruppo[0] != 'Z')
+  if (gruppo != 0)
   {
     _cont_gcs += 1;
-    set_row (_i,"@18g%s", bil->gruppo);
-    set_row (_i,"@22g%s", bil->conto);
+    set_row (_i,"@20g%d", gruppo);
+    set_row (_i,"@24g%d", conto);
     if (sottoc != 0L) // Omette la stampa dello 0
-      set_row (_i,"@26g%s", bil->sottoc);
-    set_row (_i,"@33g%s", (const char*) descr_sottoc);
-    set_row (_i,"@86g%s", (const char*) _totale);
+      set_row (_i,"@28g%ld", sottoc);
+	  const TString & descr = descrizione_sottoconto(gruppo, conto, sottoc);
+    set_row (_i,"@35g%s", (const char*) descr);
+    set_row (_i,"@88g%s", (const char*) _totale);
     _i++;
   }  
 }
 
-void BA3800_application::setta_righe_descr(TParagraph_string& str,const TString& formato,const TString& formato2)
+void BA3800_application::setta_righe_descr(const char * str, const char * formato)
 {
-  const char* r;
-  int i = 1;
+	TParagraph_string s(str, 40);
+  const char * r;
 
-  while ((r = str.get()) != NULL)
-  { 
-    if (i == 1)
-      set_row (_i,formato, r); 
-    else
-      if (i > 1)
-        set_row (_i,formato2,r);
-    _i++;           
-    i++;
-  } 
+  while ((r = s.get()) != NULL)
+		set_row (_i++, formato, r);
 }
 
 void BA3800_application::intestazione_ditta()
@@ -1691,7 +1591,6 @@ void BA3800_application::intestazione_studio()
   set_header(1,(const char*) sep);
   
   set_header (1,FR("@0gStudio"));
-  //set_header (1,"Nome dello studio");
   
   datastampastr = _datastampa.string();
 
@@ -1704,123 +1603,62 @@ void BA3800_application::intestazione_studio()
 
 const char* BA3800_application::descrizione_lettera(char sezione, char lettera)
 {
-  TTable tabivd(TAB_IVD);
-  TString16 dep, dep2;
+  TString16 key;
 
-  tabivd.zero();
-  dep.format("%1c%1c", sezione, lettera);
-  tabivd.put("CODTAB", dep);
-  tabivd.read();
-  dep2 = tabivd.get("CODTAB");
-  if (dep == dep2)
-    tmp = tabivd.get("S0");
-  else
-    tmp = "";
-  return tmp;
+  key.format("%1c%1c", sezione, lettera);
+	
+  return cache().get(TAB_IVD, key, "S0");
 }
 
 const char* BA3800_application::descrizione_numeroromano(char sezione, char lettera, int numr)
 {
-  TTable tabivd(TAB_IVD);
-  TString16 dep, dep2;
+  TString16 key;
 
-  tabivd.zero();    
-  if (numr != 0)
-    dep.format("%1c%1c%04d", sezione, lettera, numr);
+  if (numr > 0)
+    key.format("%1c%1c%04d", sezione, lettera, numr);
   else
-    dep.format("%c%c    ", sezione, lettera);
-  
-  tabivd.put("CODTAB", dep);
-  tabivd.read();
-  dep2 = tabivd.get("CODTAB");
-  if (dep == dep2)
-    tmp = tabivd.get("S0");
-  else
-    tmp = "";
-  return tmp;
+    key.format("%c%c    ", sezione, lettera);
+	
+  return cache().get(TAB_IVD, key, "S0");
 }
 
-const char* BA3800_application::descrizione_numero(char sezione, char lettera, int numr, int numero)
+const char* BA3800_application::descrizione_numero(char sezione, char lettera, int numr, const TString &  numero)
 {
-  TTable tabivd(TAB_IVD);
-  TString16 dep,dep2;
+  TString16 key;
 
-  tabivd.zero();            
-  if (numr != 0)
-    dep.format("%1c%1c%04d%02d",sezione, lettera, numr, numero);
+  if (numr > 0)
+    key.format("%1c%1c%04d%-4s",sezione, lettera, numr, (const char *) numero);
   else
-    dep.format("%c%c    %02d",sezione,lettera,numero);
-  tabivd.put("CODTAB", dep);
-  tabivd.read();   
-  dep2 = tabivd.get("CODTAB");
-  if (dep == dep2)
-    tmp = tabivd.get("S0");
-  else
-    tmp = "";
-  return tmp;
+    key.format("%1c%1c    %-4s",sezione,lettera, (const char *) numero);
+
+  return cache().get(TAB_IVD, key, "S0");
 }     
 
 const char* BA3800_application::descrizione_sottoconto(int gruppo, int conto, long sottoc)
 {
-  TLocalisamfile pconti (LF_PCON);
+  TString16 key;
 
-  pconti.zero();
-  pconti.put(PCN_GRUPPO    , gruppo);
+  key << gruppo;
   if (conto != 0)
-    pconti.put(PCN_CONTO     , conto );
+    key << '|' << conto;
   if (sottoc != 0)
-    pconti.put(PCN_SOTTOCONTO, sottoc);
-  pconti.read();
-  if (pconti.bad())
-    pconti.zero();
-  tmp = pconti.get(PCN_DESCR);
-  return tmp;
+		key << '|' <<  sottoc;
+  return cache().get(LF_PCON, key, PCN_DESCR);
 }
 
 void BA3800_application::init_sort()
 {
-  _bil = new bil_ivd;
-  _sort = new TSort (sizeof(bil_ivd));
+  _sort = new TSort(23);
   
-  _sort -> addsortkey ((char*)&(_bil->sez)    - (char*)&(_bil->sez),1);
-  _sort -> addsortkey ((char*)&(_bil->let)    - (char*)&(_bil->sez),1);
-  _sort -> addsortkey ((char*)&(_bil->numr)   - (char*)&(_bil->sez),4);
-  _sort -> addsortkey ((char*)&(_bil->num)    - (char*)&(_bil->sez),2);
-  _sort -> addsortkey ((char*)&(_bil->gruppo) - (char*)&(_bil->sez),3);
-  _sort -> addsortkey ((char*)&(_bil->conto)  - (char*)&(_bil->sez),3);
-  _sort -> addsortkey ((char*)&(_bil->sottoc) - (char*)&(_bil->sez),6);
+  _sort -> addsortkey(0,22);
   _sort->init();
 }
 
 bool BA3800_application::user_create()
 {
-  _nditte = new TLocalisamfile (LF_NDITTE);
-  _comuni = new TLocalisamfile (LF_COMUNI);
-  _unloc  = new TLocalisamfile (LF_UNLOC);
-  _anag   = new TLocalisamfile (LF_ANAG);
-  if (_liv == 'D')
-  {
-    _pconti = new TLocalisamfile (LF_PCON);
-    _clifo  = new TLocalisamfile (LF_CLIFO); 
-  }
-  
-  _tabivd = new TTable (TAB_IVD);   
-  return TRUE;
-}
-
-bool BA3800_application::user_destroy()
-{
-  delete _tabivd;
-  delete _nditte;
-  delete _comuni;
-  delete _unloc;
-  delete _anag;
-  if (_liv == 'D')
-  {
-    delete _pconti;
-    delete _clifo;
-  }
-  return TRUE;
+	open_files(LF_TAB, LF_TABCOM, LF_NDITTE, LF_COMUNI, LF_UNLOC, LF_ANAG, LF_PCON, LF_CLIFO, 0);
+	_tabivd = new TTable(TAB_IVD);
+  return true;
 }
 
 int ba3800 (int argc, char* argv[])
@@ -1834,4 +1672,3 @@ int ba3800 (int argc, char* argv[])
       error_box("Usage: BA3 -7 {D|S}");
   return 0;
 }
-
diff --git a/ba/ba4300.h b/ba/ba4300.h
index 5f766cbf1..2a17b8098 100755
--- a/ba/ba4300.h
+++ b/ba/ba4300.h
@@ -136,6 +136,9 @@
 #define FLD_IN_DESSOGDEL  201
 #define CHK_IN_NONOBBSTAT 202
 
+#define F_INTCAF					203
+#define F_DICHP 					204
+
 #define F_MAIL  203
 
 #endif // __BA4300_H
diff --git a/ba/ba4300a.uml b/ba/ba4300a.uml
index 16ed06c47..37f876b95 100755
--- a/ba/ba4300a.uml
+++ b/ba/ba4300a.uml
@@ -599,7 +599,7 @@ END
 
 STRING FLD_GD3_FIRMAT 5
 BEGIN
-  PROMPT 1 4 "Firmatario      "
+  PROMPT 1 4 "Intermediario   "
   FIELD LF_NDITTE->FIRMAT
   FLAGS "R"
   USE LF_ANAG KEY 1
@@ -610,7 +610,7 @@ BEGIN
   DISPLAY "Nome@50" RAGSOC
   OUTPUT FLD_GD3_FIRMAT CODANAGR
   OUTPUT FLD_GD3_FIRMAT_ANAGR_RAGSOC RAGSOC
-  HELP "Codice anagrafico del firmatario degli atti"
+  HELP "Codice anagrafico dell'intermediario"
   CHECKTYPE NORMAL
   WARNING "Anagrafica assente"
   ADD RUN ba4 -1
@@ -619,7 +619,7 @@ END
 STRING FLD_GD3_FIRMAT_ANAGR_RAGSOC 50
 BEGIN
   PROMPT 17 5 ""
-  HELP "Nome del firmatario degli atti"
+  HELP "Nome dell'intermediario"
   USE LF_ANAG KEY 2
   INPUT TIPOA "F"
   INPUT RAGSOC FLD_GD3_FIRMAT_ANAGR_RAGSOC
@@ -631,82 +631,104 @@ BEGIN
   ADD RUN ba4 -1
 END
 
+STRING F_INTCAF 10
+BEGIN
+  PROMPT 1 6 "Iscriz. al CAF  "
+  HELP "Nome dell'intermediario"
+	FIELD INTCAF
+  HELP "Indicare l'iscrizione al CAF dell' intermediario"
+END
+
+DATE FLD_GD3_DECCARRAPP
+BEGIN
+  PROMPT 52 6 "Decorrenza "
+  FIELD LF_NDITTE->DECCARRAPP
+  HELP "Data di decorrenza della rappresentanza legale"
+  WARNING "Data non coerente"
+  VALIDATE DATE_CMP_FUNC >= FLD_GD2_DINIZIOATT
+END
+
+LIST F_DICHP 15
+BEGIN
+  PROMPT 1 7 "Dichiarazione predisposta da "
+  FIELD DICHP
+  ITEMS "C|Contribuente"
+  ITEMS "I|Intermediario"
+  HELP "Indicare chi predispone la dichiarazione"
+END
+
 BOOLEAN CHK_GD3_ESILOR
 BEGIN
-  PROMPT 1 6 "Esenzione ILOR"
+  PROMPT 1 9 "Esenzione ILOR"
   FIELD LF_NDITTE->ESILOR
   HELP "Indicare se la ditta e' soggetta ad esenzione ILOR"
 END
 
 BOOLEAN CHK_GD3_REGSTATSP
 BEGIN
-  PROMPT 27 6 "Statuto speciale"
+  PROMPT 27 9 "Statuto speciale"
   FIELD LF_NDITTE->REGSTATSP
   HELP "Indicare se la regione di residenza e' a statuto speciale"
 END
 
 BOOLEAN CHK_GD3_AZCONIUG
 BEGIN
-  PROMPT 54 6 "Azienda coniugale"
+  PROMPT 54 9 "Azienda coniugale"
   FIELD LF_NDITTE->AZCONIUG
   HELP "Indicare se si tratta di impresa coniugale"
 END
 
 BOOLEAN CHK_GD3_CONDFAM
 BEGIN
-  PROMPT 1 7 "Conduzione familiare"
+  PROMPT 1 10 "Conduzione familiare"
   FIELD LF_NDITTE->CONDFAM
   HELP "Indicare se la ditta e' a conduzione familiare"
 END
 
 BOOLEAN CHK_GD3_DEDART13
 BEGIN
-  PROMPT 27 7 "Deduzioni art.120 C2"
+  PROMPT 27 10 "Deduzioni art.120 C2"
   FIELD LF_NDITTE->DEDART13
   HELP "Indicare se la ditta ha diritto a deduzioni ex articolo 13"
 END
 
 BOOLEAN CHK_GD3_RICSUP20
 BEGIN
-  PROMPT 54 7 "Ricavi > 20%"
+  PROMPT 54 10 "Ricavi > 20%"
   FIELD LF_NDITTE->RICSUP20%
   HELP "Indicare se i ricavi sono superiore al 20%"
 END
 
-LIST FLD_GD3_CARRAPP 23
+LIST FLD_GD3_CARRAPP 31
 BEGIN
-  PROMPT 1 8 "Carica          "
+  PROMPT 1 11 "Carica          "
   FIELD LF_NDITTE->CARRAPP
   HELP "Codice della carica del rappresentante legale"
   ITEMS " |Nessun rappresentante"
   MESSAGE RESET,4@|DISABLE,4@
-  ITEMS "1|Rappresentante legale"
+  ITEMS "1|1 - Rappresentante legale"
   MESSAGE ENABLE,4@
-  ITEMS "2|Curatore fallimentare"
+  ITEMS "2|2 - Rappresentante di minore"
   MESSAGE ENABLE,4@
-  ITEMS "3|Liquidatore"
+  ITEMS "3|3 - Curatore fallimentare"
   MESSAGE ENABLE,4@
-  ITEMS "4|Socio amministratore"
+  ITEMS "4|4 - Commissario liquidatore"
   MESSAGE ENABLE,4@
-  ITEMS "5|Erede"
+  ITEMS "5|5 - Commissario giudiziale"
   MESSAGE ENABLE,4@
-  ITEMS "6|Curatore di eredita'"
+  ITEMS "6|6 - Rappr.fiscale sogg.non res."
+  MESSAGE ENABLE,4@
+  ITEMS "7|7 - Erede"
+  MESSAGE ENABLE,4@
+  ITEMS "8|8 - Liquidatore (Liquid.vol.)"
+  MESSAGE ENABLE,4@
+  ITEMS "9|9 - Soggetto tenuto alla pres."
   MESSAGE ENABLE,4@
-END
-
-DATE FLD_GD3_DECCARRAPP
-BEGIN
-  PROMPT 50 8 "Decorrenza   "
-  FIELD LF_NDITTE->DECCARRAPP
-  GROUP 4
-  HELP "Data di decorrenza della rappresentanza legale"
-  WARNING "Data non coerente"
-  VALIDATE DATE_CMP_FUNC >= FLD_GD2_DINIZIOATT
 END
 
 STRING FLD_GD3_RAPPR 5
 BEGIN
-  PROMPT 1 9 "Rappresentante  "
+  PROMPT 1 12 "Rappresentante  "
   FIELD LF_NDITTE->RAPPR
   FLAGS "R"
   GROUP 4
@@ -724,7 +746,7 @@ END
 
 STRING FLD_GD3_RAPPR_ANAGR_RAGSOC 50
 BEGIN
-  PROMPT 17 10 ""
+  PROMPT 17 13 ""
   HELP "Nome del rappresentate legale"
   COPY USE FLD_GD3_FIRMAT_ANAGR_RAGSOC
   INPUT RAGSOC FLD_GD3_RAPPR_ANAGR_RAGSOC
@@ -737,26 +759,26 @@ END
 
 TEXT DLG_NULL
 BEGIN
-  PROMPT 1 11 "Denominazione Estesa"
+  PROMPT 1 14 "Denominazione Estesa"
 END
 
 STRING FLD_DE_DENEST1 70
 BEGIN
-  PROMPT 3 12 ""
+  PROMPT 3 15 ""
   FIELD LF_NDITTE->DENEST1
   HELP "Denominazione estesa della ditta"
 END
 
 STRING FLD_DE_DENEST2 70
 BEGIN
-  PROMPT 3 13 ""
+  PROMPT 3 16 ""
   FIELD LF_NDITTE->DENEST2
   HELP "Denominazione estesa della ditta"
 END
 
 STRING FLD_DE_DENEST3 70
 BEGIN
-  PROMPT 3 14 ""
+  PROMPT 3 17 ""
   FIELD LF_NDITTE->DENEST3
   HELP "Denominazione estesa della ditta"
 END
diff --git a/ba/bacnv.cpp b/ba/bacnv.cpp
index 5a4c879cd..dac81fd54 100755
--- a/ba/bacnv.cpp
+++ b/ba/bacnv.cpp
@@ -21,13 +21,14 @@
 #include <causali.h>
 #include <clifo.h>
 #include <mov.h>
+#include <pconti.h>
 #include <rmov.h>
 #include <saldi.h>
 
 #include "..\cg\cglib02.h"
 
 
-#define usage "Errore - uso : bacnv [1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21] ditta"
+#define usage "Errore - uso : bacnv [1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22] ditta"
 
 ///////////////////////////////////////////////////////////////////////////////////////////////////////
 // Applicazione di conversione archivi XBase, valida per tutti e 4 i tipi di DLL
@@ -195,6 +196,7 @@ public:
   void change_ca7(TRectype& rec) const;
   void convert_quadst() const; 
   void convert_clifo_privati(); 
+	void convert_pcon_ivd();
 
   
   TConversione_archivi() : _oldditta(0), _codditta(0), _error(0) {}
@@ -355,6 +357,9 @@ bool TConversione_archivi::menu(MENU_TAG)
     break;
   case 21:
 		convert_clifo_privati(); 
+    break;
+  case 22:
+		convert_pcon_ivd(); 
   default:
     break;  
 }
@@ -1860,6 +1865,71 @@ void TConversione_archivi::convert_clifo_privati()
 		prefix().set(pref);
 }
 
+////////////////////////////////////////////////////////////////
+// Effettua conversione campo NUMIVD E NUMIVDOPP sul piano dei conti
+////////////////////////////////////////////////////////////////
+
+void TConversione_archivi::convert_pcon_ivd()
+{ 
+  long firm = get_firm();             
+  TString pref;
+
+  if (firm == 0)
+		pref = prefix().name();
+ 
+	TLocalisamfile ditte(LF_NDITTE);
+  
+  for (ditte.first(); !ditte.eof(); ditte.next())
+  {
+    const long codditta = ditte.get_long("CODDITTA");
+    
+    if (prefix().exist(codditta))
+    {
+      set_firm(codditta);
+		  
+			{
+				TRelation rel(LF_PCON);
+				TRectype& curr = rel.curr();
+
+				TCursor cursore(&rel);
+			  const long items = cursore.items();
+				cursore.freeze();
+
+				TProgind pi(items, "Conversione Codici IV Direttiva CEE..", FALSE, TRUE);
+
+				for (cursore=0; cursore.pos()<items; ++cursore)
+			  {
+					pi.addstatus(1);                                     
+					TString16 numivd = curr.get(PCN_NUMIVD);
+					bool rew = false;
+					
+					if (numivd.len() == 1)
+					{
+						numivd.insert("0");
+						curr.put(PCN_NUMIVD, numivd);
+						rew = true;
+					}
+
+					TString16 numivdopp = curr.get(PCN_NUMIVDOPP);
+					
+					if (numivdopp.len() == 1)
+					{
+						numivdopp.insert("0");
+						curr.put(PCN_NUMIVDOPP, numivdopp);
+						rew = true;
+					}
+					if (rew)
+						rel.rewrite();
+				}
+			}
+    }
+  }
+  if (firm > 0)
+		set_firm(firm);
+  else
+		prefix().set(pref);
+}
+
 ///////////////////////////////////////////////////////////
 // Programma di conversione archivi speciale
 ///////////////////////////////////////////////////////////
@@ -1868,7 +1938,7 @@ int main(int argc,char** argv)
 {
   const int r = (argc > 1) ? abs(atoi(argv[1])) : 0;
   
-  if (r < 0 || r > 21)
+  if (r < 0 || r > 22)
   {
     error_box(usage);
     return 100;
diff --git a/ba/bastivd.uml b/ba/bastivd.uml
index 6c4595468..9afa8dbb7 100755
--- a/ba/bastivd.uml
+++ b/ba/bastivd.uml
@@ -16,16 +16,16 @@ BEGIN
   INPUT CODTAB[1,1] F_INIZIO1
   INPUT CODTAB[2,2] F_INIZIO2
   INPUT CODTAB[3,6] F_INIZIO3
-  INPUT CODTAB[7,8] F_INIZIO4
+  INPUT CODTAB[7,10] F_INIZIO4
   DISPLAY "Sezione" CODTAB[1,1]
   DISPLAY "Lettera" CODTAB[2,2]
   DISPLAY "Classe  " CODTAB[3,6]
-  DISPLAY "Numero" CODTAB[7,8]
+  DISPLAY "Numero" CODTAB[7,10]
   DISPLAY "Descrizione@50" S0
   OUTPUT F_INIZIO1 CODTAB[1,1]
   OUTPUT F_INIZIO2 CODTAB[2,2]
   OUTPUT F_INIZIO3 CODTAB[3,6]
-  OUTPUT F_INIZIO4 CODTAB[7,8]
+  OUTPUT F_INIZIO4 CODTAB[7,10]
   GROUP 1
 END
 
@@ -47,11 +47,10 @@ BEGIN
   GROUP 1
 END
 
-NUMBER F_INIZIO4 2
+STRING F_INIZIO4 4
 BEGIN
   PROMPT 52 2 "Numero  "
-  FLAGS "RZ"
-  FIELD FROM[7,8]
+  FIELD CODTAB[7,10]
   COPY ALL F_INIZIO1
   GROUP 1
 END
@@ -70,12 +69,12 @@ BEGIN
   INPUT CODTAB[1,1] F_FINE1
   INPUT CODTAB[2,2] F_FINE2
   INPUT CODTAB[3,6] F_FINE3
-  INPUT CODTAB[7,8] F_FINE4
+  INPUT CODTAB[7,10] F_FINE4
   COPY DISPLAY F_INIZIO1
   OUTPUT F_FINE1 CODTAB[1,1]
   OUTPUT F_FINE2 CODTAB[2,2]
   OUTPUT F_FINE3 CODTAB[3,6]
-  OUTPUT F_FINE4 CODTAB[7,8]
+  OUTPUT F_FINE4 CODTAB[7,10]
   GROUP 2
 END
 
@@ -97,11 +96,10 @@ BEGIN
   GROUP 2
 END
 
-NUMBER F_FINE4 2
+STRING F_FINE4 4
 BEGIN
   PROMPT 52 5 "Numero  "
-  FLAGS "RZ"
-  FIELD TO[7,8]
+  FIELD CODTAB[7,10]
   COPY ALL F_FINE1
   GROUP 2
 END
@@ -118,4 +116,3 @@ END
 
 ENDPAGE
 ENDMASK
-
diff --git a/ba/batbivd.uml b/ba/batbivd.uml
index c3b10f6a9..d616df31b 100755
--- a/ba/batbivd.uml
+++ b/ba/batbivd.uml
@@ -53,7 +53,7 @@ BEGIN
   FIELD %IVD->CODTAB[3,6]
   FLAGS "MZ"
   KEY 1
-  USE %IVD SELECT CODTAB[7,8]==""
+  USE %IVD SELECT CODTAB[7,10]==""
   COPY INPUT F_LETT
   INPUT CODTAB[3,6] F_CLASSE
   DISPLAY "Sezione" CODTAB[1,1]
@@ -75,21 +75,20 @@ BEGIN
   FLAGS "D"
 END
 
-NUMBER F_NUM 2
+STRING F_NUM 4
 BEGIN
   PROMPT 1 7 "Numero  "
-  FIELD %IVD->CODTAB[7,8]
-  FLAGS "RZ"
+  FIELD %IVD->CODTAB[7,10]
   KEY 1
   USE %IVD
   COPY INPUT F_CLASSE
-  INPUT CODTAB[7,8] F_NUM
+  INPUT CODTAB[7,10] F_NUM
   DISPLAY "Sezione" CODTAB[1,1]
   DISPLAY "Lettera" CODTAB[2,2]
   DISPLAY "Classe  @M" CODTAB[3,6]
-  DISPLAY "Numero" CODTAB[7,8]
+  DISPLAY "Numero" CODTAB[7,10]
   DISPLAY "Descrizione@50" S0
-  OUTPUT F_NUM CODTAB[7,8]
+  OUTPUT F_NUM CODTAB[7,10]
   OUTPUT F_SEZ CODTAB[1,1]
   OUTPUT F_LETT CODTAB[2,2]
   OUTPUT F_CLASSE CODTAB[3,6]
@@ -114,7 +113,7 @@ BEGIN
   DISPLAY "Sezione" CODTAB[1,1]
   DISPLAY "Lettera" CODTAB[2,2]
   DISPLAY "Classe  @M" CODTAB[3,6]
-  DISPLAY "Numero" CODTAB[7,8]
+  DISPLAY "Numero" CODTAB[7,10]
   COPY OUTPUT F_NUM
   CHECKTYPE REQUIRED
   WARNING "Manca la descrizione"
diff --git a/ba/batbreg.h b/ba/batbreg.h
index 650dd15d6..45ac1eb00 100755
--- a/ba/batbreg.h
+++ b/ba/batbreg.h
@@ -77,3 +77,6 @@
 #define GRP_NOGIORNMAG 12
 #define GRP_SOLOGIORNALE 13
 #define GRP_NOGIORNALE 14
+
+#define GRP_INTENTI 15
+#define GRP_NOINTENTI 16
diff --git a/ba/batbreg.uml b/ba/batbreg.uml
index 1e2d70a62..4d7fdcf0b 100755
--- a/ba/batbreg.uml
+++ b/ba/batbreg.uml
@@ -146,6 +146,8 @@ BEGIN
   ITEM "9|9) Giornale di magazzino"
     MESSAGE HIDE,GRP_VENDITE@|HIDE,GRP_ACQUISTI@|HIDE,GRP_RIEPIVA@|HIDE,GRP_INCASSI@|HIDE,GRP_GIORNALE@|HIDE,GRP_LSOCIALI@|HIDE,GRP_CESPITI@|HIDE,GRP_INVENTARI@|SHOW,GRP_GIORNMAG@
     MESSAGE "",GRP_NOGIORNMAG@|"",F_ATTIVITA
+  ITEM "10|10) Dichiarazione d'intenti"
+    MESSAGE HIDE,GRP_NOINTENTI@|SHOW,GRP_INTENTI@
 END
 
 STRING F_CONSPRESSO 50
@@ -161,7 +163,7 @@ BEGIN
   PROMPT 1 8 "Codice attivita'  "
   FIELD S8
   FLAGS "URZ"
-  GROUP GRP_VENDITE GRP_ACQUISTI GRP_RIEPIVA
+  GROUP GRP_VENDITE GRP_ACQUISTI GRP_RIEPIVA GRP_NOINTENTI
   USE LF_ATTIV
   INPUT CODDITTA F_CODDITTA SELECT
   INPUT CODATT F_ATTIVITA
@@ -178,7 +180,7 @@ NUMBER F_CODULC 3
 BEGIN
   PROMPT 35 8 "Unita' locale           "
   FLAGS "R"
-  GROUP GRP_VENDITE GRP_ACQUISTI GRP_RIEPIVA  GRP_INCASSI  GRP_GIORNALE  GRP_LSOCIALI GRP_GIORNMAG
+  GROUP GRP_VENDITE GRP_ACQUISTI GRP_RIEPIVA  GRP_INCASSI  GRP_GIORNALE  GRP_LSOCIALI GRP_GIORNMAG GRP_NOINTENTI
   FIELD I7
   USE LF_UNLOC
     JOIN LF_COMUNI TO LF_UNLOC KEY 1 INTO COM=COMULC
@@ -201,12 +203,20 @@ BEGIN
   PROMPT 1 10 "Pagine stampate   "
   HELP "Numero di pagine gia' stampate"
   FIELD I1
-  GROUP 1
+  GROUP 1 
+END
+
+DATE F_ULTIMA_DATA_DI_STAMPA
+BEGIN
+  PROMPT 26 10 "Ultima data di stampa "
+  HELP "Data dell'ultima stampa effettuata"
+  FIELD D3
+	GROUP 1
 END
 
 NUMBER F_PAGNUM 5
 BEGIN
-  PROMPT 35 10 "Pagine numerate       "
+  PROMPT 60 10 "Pagine numerate "
   HELP "numero di pagine di cui e' stata stampata la numerazione"
   FIELD I2
   GROUP 1
@@ -216,6 +226,7 @@ BOOLEAN F_STAMPA_NUMERI
 BEGIN
   PROMPT 1 11 "Stampa numeri di pagina durante la stampa del registro"
   FIELD S11
+	GROUP 1
 END
 
 DATE F_DATAVID
@@ -240,7 +251,7 @@ BEGIN
   FIELD S6
   HELP "Codice del libro unico a cui fa riferimento"
   FLAGS "UZ"
-  GROUP GRP_VENDITE GRP_ACQUISTI GRP_RIEPIVA
+  GROUP GRP_VENDITE GRP_ACQUISTI GRP_RIEPIVA GRP_NOINTENTI
   USE %LBU
   INPUT CODTAB[1,4] F_ANNO
   INPUT CODTAB[5,7] F_CODLBU
@@ -257,11 +268,13 @@ END
 BOOLEAN F_CONFIG
 BEGIN
   PROMPT 1 17 "Stampante configurata"
+	GROUP GRP_NOINTENTI
 END
 
 BUTTON F_PRINTER 30 2
 BEGIN
   PROMPT 40 17 "Configurazione ~stampante"
+	GROUP GRP_NOINTENTI
 END
 
 ENDPAGE
@@ -307,7 +320,7 @@ BOOLEAN F_REGSOSP
 BEGIN
   PROMPT 1 5 "Registro in sospensione "
   FIELD B1
-  GROUP GRP_VENDITE GRP_ACQUISTI GRP_NOGIORNMAG
+  GROUP GRP_VENDITE GRP_ACQUISTI GRP_NOGIORNMAG 
   HELP "Indicare se il registro e' in sospensione d'imposta"
   MESSAGE TRUE ENABLE,F_REGSOSPEXT
   MESSAGE FALSE CLEAR,F_REGSOSPEXT
@@ -486,16 +499,9 @@ BEGIN
   GROUP GRP_VENDITE GRP_ACQUISTI GRP_INCASSI  GRP_GIORNALE
 END
 
-DATE F_ULTIMA_DATA_DI_STAMPA
-BEGIN
-  PROMPT 1 17 "Ultima data di stampa           "
-  HELP "Data dell'ultima stampa effettuata"
-  FIELD D3
-END
-
 BOOLEAN F_STAMPA_INTESTAZIONE
 BEGIN
-  PROMPT 46 17 "Stampa intestazione ditta"
+  PROMPT 1 17 "Stampa intestazione ditta"
   HELP "Indicare se stampare l'intestazione della ditta"
   FIELD B9
   GROUP 1
diff --git a/ba/cgarea.men b/ba/cgarea.men
index 4242fd152..d91fa5a97 100755
--- a/ba/cgarea.men
+++ b/ba/cgarea.men
@@ -5,5 +5,5 @@ Module  = 0
 Item_01 = "Contabilita' generale", <cgmenu.men>
 Item_02 = "Gestione cespiti", <cemenu.men>
 Item_03 = "Gestione percipienti", <77menu.men>
-Item_04 = "Contabilita' analitica", <camenu.men>
-Item_05 = "Elenchi Intracomunitari", <inmenu.men>
+Item_04 = "Elenchi Intracomunitari", <inmenu.men>
+Item_05 = "Dichiarazioni d'intento", <limenu.men>
diff --git a/ba/f9.dir b/ba/f9.dir
index d7c5be63e..aafe77aee 100755
--- a/ba/f9.dir
+++ b/ba/f9.dir
@@ -1,3 +1,3 @@
 9
 1
-%nditte|0|0|560|0|Ditte|#6||
+%nditte|0|0|571|0|Ditte|#6||
diff --git a/ba/f9.trr b/ba/f9.trr
index b792873b2..2782fb715 100755
--- a/ba/f9.trr
+++ b/ba/f9.trr
@@ -1,5 +1,5 @@
 9
-53
+55
 CODDITTA|3|5|0|
 TIPOA|1|1|0|
 CODANAGR|3|5|0|
@@ -53,6 +53,8 @@ FREQACQ|1|1|0|Frequenza riepiloghi acquisti INTRA
 TIPOSOGDEL|1|1|0|Tipo anagrafico del soggetto delegato
 CODSOGDEL|3|6|0|Codice del soggetto delegato
 NONOBBSTAT|8|1|0|Non obbligato alla compilazione del valore statistico se mensile
+INTCAF|1|10|0|N.ro Iscrizione al CAF dell'intemediario (firmatario)
+DICHP|1|1|0|Dichiarazione predisposta da <C>ontribuente, <I>ntermediario
 4
 CODDITTA| 
 UPPER(RAGSOC)|X
diff --git a/ce/ce1500.cpp b/ce/ce1500.cpp
index 220fad087..20bed7b4e 100755
--- a/ce/ce1500.cpp
+++ b/ce/ce1500.cpp
@@ -240,7 +240,7 @@ void TMov_qmask::on_firm_change()
 TMov_qmask::TMov_qmask() : TAutomask("ce1500a") 
 {
   first_focus(F_IDMOV);
-  create_fields(1, 14, F_USER);
+  create_fields(1, 9, F_USER);
 }
 
 //metodo per la generazione dei campi di ricerca personalizzati
diff --git a/ce/ce1500a.uml b/ce/ce1500a.uml
index 32635a665..27b0a5b58 100755
--- a/ce/ce1500a.uml
+++ b/ce/ce1500a.uml
@@ -8,20 +8,20 @@ ENDPAGE
 
 PAGE "Movimenti cespiti" -1 -1 78 18
 
-GROUPBOX DLG_NULL 78 5
+GROUPBOX DLG_NULL 78 8
 BEGIN
-  PROMPT 0 1 "@bParametri ditta"
+  PROMPT 0 0 "@bParametri di selezione"
 END
 
 NUMBER F_DITTA 5
 BEGIN
-  PROMPT 1 2 "Ditta     "
+  PROMPT 1 1 "Ditta     "
   FLAGS "DF"
 END
 
 STRING F_RAGSOC 50
 BEGIN
-  PROMPT 26 2 ""
+  PROMPT 26 1 ""
   USE LF_NDITTE
   INPUT CODDITTA F_DITTA
   OUTPUT F_RAGSOC RAGSOC
@@ -31,7 +31,7 @@ END
 
 NUMBER F_ESERCIZIO 4
 BEGIN
-  PROMPT 1 3 "Esercizio "
+  PROMPT 1 2 "Esercizio "
   FLAGS "AZ"
   USE CCE
   JOIN ESC ALIAS 104 INTO CODTAB==CODTAB
@@ -47,25 +47,25 @@ END
 
 DATE F_INIZIO_ES
 BEGIN
-  PROMPT 26 3 "Inizio "
+  PROMPT 26 2 "Inizio "
   FLAGS "D"
 END
 
 DATE F_FINE_ES
 BEGIN
-  PROMPT 50 3 "Fine "
+  PROMPT 50 2 "Fine "
   FLAGS "D"
 END
 
 NUMBER F_GRUPPO 2
 BEGIN
-  PROMPT 1 4 "Gruppo    "
+  PROMPT 1 3 "Gruppo    "
   FLAGS "Z"
 END
 
 STRING F_SPECIE 4
 BEGIN
-  PROMPT 16 4 "Specie "
+  PROMPT 16 3 "Specie "
   FLAGS "_"
   USE CCB 
   JOIN %CAT ALIAS 400 INTO CODTAB=CODTAB[5,10]
@@ -84,18 +84,13 @@ END
 
 STRING F_DESC_GRSP 60 45
 BEGIN
-  PROMPT 31 4 ""
+  PROMPT 31 3 ""
   FLAGS "D"
 END
 
-GROUPBOX DLG_NULL 78 4
-BEGIN
-  PROMPT 0 6 "@bSelezione per..."
-END
-
 NUMBER F_IMPIANTO 10
 BEGIN
-  PROMPT 1 7 "Impianto "
+  PROMPT 1 4 "Impianto  "
   FLAGS "Z"
   USE CIM
   INPUT CODTAB F_IMPIANTO
@@ -106,9 +101,9 @@ BEGIN
   CHECKTYPE NORMAL
 END
 
-STRING F_DESC_IMP 50
+STRING F_DESC_IMP 50 48
 BEGIN
-  PROMPT 24 7 ""
+  PROMPT 27 4 ""
   FLAGS "Z"
   USE CIM KEY 2
   INPUT S0 F_DESC_IMP
@@ -120,7 +115,7 @@ END
 
 STRING F_IDCESPITE 10
 BEGIN
-  PROMPT 1 8 "Cespite  "
+  PROMPT 1 5 "Cespite   "
   FLAGS "UZ"
   USE LF_CESPI 
   INPUT IDCESPITE F_IDCESPITE
@@ -137,9 +132,9 @@ BEGIN
   CHECKTYPE NORMAL
 END
 
-STRING F_DESC_CES 50
+STRING F_DESC_CES 50 48
 BEGIN
-  PROMPT 24 8 ""
+  PROMPT 27 5 ""
   USE LF_CESPI KEY 2
   INPUT DESC F_DESC_CES
   DISPLAY "Desc@50" DESC
@@ -156,7 +151,7 @@ END
 
 NUMBER F_IDMOV 11
 BEGIN
-  PROMPT 1 10 "Movimento "
+  PROMPT 1 6 "Movimento "
   FLAGS "Z"
   USE LF_MOVCE
   JOIN LF_CESPI INTO IDCESPITE==IDCESPITE
@@ -179,15 +174,15 @@ BEGIN
   KEY 1
 END
 
-STRING F_DESC_MOV 50
+STRING F_DESC_MOV 50 48
 BEGIN
-  PROMPT 27 10 ""
+  PROMPT 27 6 ""
   FLAGS "D"
 END
 
 NUMBER F_NUMREG 7
 BEGIN
-  PROMPT 1 11 "Selezione per numero di registrazione di prima nota "
+  PROMPT 1 14 "Selezione per numero di registrazione di prima nota "
   USE LF_MOVCE KEY 3
   JOIN LF_CESPI INTO IDCESPITE==IDCESPITE
   INPUT NUMREG F_NUMREG 
@@ -206,7 +201,7 @@ END
 
 SPREADSHEET F_CGROWS 0 -2
 BEGIN
-  PROMPT 0 12 ""
+  PROMPT 0 15 ""
   ITEM "Importo@18"
   ITEM "Residuo@18"
   ITEM "Gruppo"
@@ -230,9 +225,9 @@ BEGIN
   GROUP 8
 END
 
-GROUPBOX DLG_NULL 78 10
+GROUPBOX DLG_NULL 78 6
 BEGIN
-  PROMPT 0 13 "@bRicerce personalizzate"
+  PROMPT 0 8 "@bRicerche personalizzate"
 END
 
 ENDPAGE
diff --git a/ce/ce2200.cpp b/ce/ce2200.cpp
index b14b8992b..8d2884960 100755
--- a/ce/ce2200.cpp
+++ b/ce/ce2200.cpp
@@ -126,7 +126,7 @@ protected:
   void incr_zero(TRectype& rec, const char* val, const char* valp) const;
 
 public:   
-  void crea_esercizio(int oldes, int newes, const TDate& ies, const TDate& fes) const;
+  bool crea_esercizio(int oldes, int newes, const TDate& ies, const TDate& fes) const;
   void crea_attivita(int oldes, int newes) const;
   void crea_registro(int oldes, int newes) const;
   void crea_categorie(int oldes, int newes) const;
@@ -164,7 +164,7 @@ real TOpenesc::calc_coeff(const TDate& ies, const TDate& fes) const
   return coeff;
 }
 
-void TOpenesc::crea_esercizio(int oldes, int newes, const TDate& ies, const TDate& fes) const
+bool TOpenesc::crea_esercizio(int oldes, int newes, const TDate& ies, const TDate& fes) const
 { 
   // Crea l'esercizio contabile se necessario
   TTable esc("ESC");
@@ -185,7 +185,8 @@ void TOpenesc::crea_esercizio(int oldes, int newes, const TDate& ies, const TDat
       }
     }
     else
-      warning_box(TR("Attenzione: non esiste ancora l'esercizio contabile %04d"), newes);
+      return error_box(TR("Attenzione: non esiste ancora l'esercizio contabile %04d"), newes);
+
   }
   
   // Crea l'esercizio cespiti se necessario
@@ -213,6 +214,8 @@ void TOpenesc::crea_esercizio(int oldes, int newes, const TDate& ies, const TDat
     cce.rewrite();
   else
     cce.write();
+
+  return true;
 }
 
 void TOpenesc::crea_attivita(int oldes, int newes) const
@@ -408,13 +411,15 @@ void TOpenesc::main_loop()
     const int newes = m.get_int(F_NEWES);
     const TDate ies(m.get(F_NEWINIZIO));
     const TDate fes(m.get(F_NEWFINE));
-    crea_esercizio(oldes, newes, ies, fes);
-    crea_attivita(oldes, newes);
-    crea_registro(oldes, newes);
-    crea_categorie(oldes, newes);
-    crea_saldi(oldes, newes);
-    crea_ammortamenti(oldes, newes);
-    ditta_cespiti().set_attivita(newes, 0, NULL);
+    if (crea_esercizio(oldes, newes, ies, fes))
+    {
+      crea_attivita(oldes, newes);
+      crea_registro(oldes, newes);
+      crea_categorie(oldes, newes);
+      crea_saldi(oldes, newes);
+      crea_ammortamenti(oldes, newes);
+      ditta_cespiti().set_attivita(newes, 0, NULL);
+    }
   }
 }
 
diff --git a/cg/cg0100.cpp b/cg/cg0100.cpp
index 891a73203..dfd5d7612 100755
--- a/cg/cg0100.cpp
+++ b/cg/cg0100.cpp
@@ -228,8 +228,8 @@ void TPianoconti_app::init_insert_mode(TMask& m)
       else
         s3.right_just(4,'0');
 
-      if (!s4.empty())
-        s4.right_just(2,'0');
+//      if (!s4.empty())
+//        s4.right_just(2,'0');
 
       key.format("%1d%1s%s%s", s1, (const char*) s2,(const char*) s3, (const char*) s4);
       s5 = cache().get("%IVD", key, "S0");
diff --git a/cg/cg0100a.uml b/cg/cg0100a.uml
index 9d27dae37..d455f509a 100755
--- a/cg/cg0100a.uml
+++ b/cg/cg0100a.uml
@@ -18,7 +18,7 @@ NUMBER FLD_CM1_GRUPPO 3
 BEGIN
   PROMPT 2 1 "Gruppo     "
   HELP "Codice del gruppo"
-  FIELD LF_PCON->GRUPPO
+  FIELD GRUPPO
   FLAGS "R"
   KEY 1
   USE LF_PCON KEY 1 SELECT CONTO=""
@@ -40,7 +40,7 @@ NUMBER FLD_CM1_CONTO 3
 BEGIN
   PROMPT 2 2 "Conto      "
   HELP "Codice dell'eventuale conto"
-  FIELD LF_PCON->CONTO
+  FIELD CONTO
   FLAGS "R"
   KEY 1
   USE LF_PCON KEY 1 SELECT ((CONTO!="")&&(SOTTOCONTO=""))
@@ -67,7 +67,7 @@ NUMBER FLD_CM1_SOTTOCONTO 6
 BEGIN
   PROMPT 2 3 "Sottoconto "
   HELP "Codice dell'eventuale sottoconto"
-  FIELD LF_PCON->SOTTOCONTO
+  FIELD SOTTOCONTO
   KEY 1
   USE LF_PCON KEY 1 SELECT SOTTOCONTO!=""
   COPY INPUT FLD_CM1_CONTO
@@ -97,7 +97,7 @@ END
 STRING FLD_CM1_DESC 50
 BEGIN
   PROMPT 24 3 ""
-  FIELD LF_PCON->DESCR
+  FIELD DESCR
   KEY 2
   USE LF_PCON KEY 2
   INPUT DESCR FLD_CM1_DESC
@@ -116,7 +116,7 @@ NUMBER FLD_CM1_CODTABANALISI 12
 BEGIN
   PROMPT 1 5 "Codice Tabella Analisi "
   HELP "Codice di raggruppamento per l'analisi di bilancio"
-  FIELD LF_PCON->CODCBL
+  FIELD CODCBL
   USE LF_ABPCON
   INPUT CODCBL FLD_CM1_CODTABANALISI
   DISPLAY "Codice@12" CODCBL
@@ -148,7 +148,7 @@ END
 LIST FLD_CM1_INDBIL 1 22
 BEGIN
   PROMPT 1 6 "Sezione di bilancio    "
-  FIELD LF_PCON->INDBIL
+  FIELD INDBIL
   GROUP 1 3
   HELP "Sezione di appartenenza del conto"
   ITEM "1|1. Attivita'"
@@ -161,7 +161,7 @@ END
 LIST FLD_CM1_SEZIVD 1 22
 BEGIN
   PROMPT 1 7 "Sez. e classe IV dir.  "
-  FIELD LF_PCON->SEZIVD
+  FIELD SEZIVD
   ITEM "0|0. Nessuna" MESSAGE CLEAR,5@|CLEAR,6@
   ITEM "1|1. Attivita'" MESSAGE ENABLE,5@|ENABLE,6@
   ITEM "2|2. Passivita'" MESSAGE ENABLE,5@|ENABLE,6@
@@ -175,64 +175,63 @@ END
 
 STRING FLD_CM1_LETTIVD 1 1
 BEGIN
-  PROMPT 57 7 ""
+  PROMPT 56 7 ""
   HELP "Codice del conto secondo la IV direttiva CEE"
-  FIELD LF_PCON->LETTIVD
+  FIELD LETTIVD
   GROUP 1 5
   FLAGS "U"
 END
 
 STRING FLD_CM1_LETTIVDH 1
 BEGIN
-  PROMPT 57 7 ""
+  PROMPT 55 7 ""
   FLAGS "HDU"
   GROUP 1 5
 END
 
 NUMBER FLD_CM1_NUMRIVD 8 4
 BEGIN
-  PROMPT 61 7 ""
+  PROMPT 59 7 ""
   HELP "Codice del conto secondo la IV direttiva CEE"
-  FIELD LF_PCON->NUMRIVD
+  FIELD NUMRIVD
   GROUP 1 5
   FLAGS "MZ"
 END
 
 NUMBER FLD_CM1_NUMRIVDH 8 4
 BEGIN
-  PROMPT 61 7 ""
+  PROMPT 59 7 ""
   FLAGS "HDMZ"
   GROUP  1 5
 END
 
-NUMBER FLD_CM1_NUMIVD 2
+STRING FLD_CM1_NUMIVD 4
 BEGIN
-  PROMPT 72 7 ""
-  FIELD LF_PCON->NUMIVD
-  FLAGS "Z"
+  PROMPT 70 7 ""
+  FIELD NUMIVD
   GROUP 1 5
   USE %IVD
   INPUT CODTAB[1,1] FLD_CM1_SEZIVD
   INPUT CODTAB[2,2] FLD_CM1_LETTIVD
   INPUT CODTAB[3,6] FLD_CM1_NUMRIVD
-  INPUT CODTAB[7,8] FLD_CM1_NUMIVD
+  INPUT CODTAB[7,10] FLD_CM1_NUMIVD
   DISPLAY "Sezione" CODTAB[1,1]
   DISPLAY "Lettera" CODTAB[2,2]
   DISPLAY "Classe  @M" CODTAB[3,6]
-  DISPLAY "Numero" CODTAB[7,8]
+  DISPLAY "Numero" CODTAB[7,10]
   DISPLAY "Descrizione@50" S0
   OUTPUT FLD_CM1_SEZIVD CODTAB[1,1]
   OUTPUT FLD_CM1_LETTIVD CODTAB[2,2]
   OUTPUT FLD_CM1_NUMRIVD CODTAB[3,6]
-  OUTPUT FLD_CM1_NUMIVD CODTAB[7,8]
+  OUTPUT FLD_CM1_NUMIVD CODTAB[7,10]
   OUTPUT FLD_CM1_DESCIVD S0
   CHECKTYPE NORMAL
   WARNING "Codice non presente"
 END
 
-NUMBER FLD_CM1_NUMIVDH 2
+STRING FLD_CM1_NUMIVDH 4
 BEGIN
-  PROMPT 72 7 ""
+  PROMPT 70 7 ""
   FLAGS "HDZ"
   GROUP 1 5
 END
@@ -246,7 +245,7 @@ BEGIN
   DISPLAY "Sezione" CODTAB[1,1]
   DISPLAY "Lettera" CODTAB[2,2]
   DISPLAY "Classe  @M" CODTAB[3,6]
-  DISPLAY "Numero" CODTAB[7,8]
+  DISPLAY "Numero" CODTAB[7,10]
   COPY OUTPUT FLD_CM1_NUMIVD
   CHECKTYPE NORMAL
   GROUP 1 5
@@ -262,7 +261,7 @@ END
 LIST FLD_CM1_SEZIVDOPP 1 22
 BEGIN
   PROMPT 1 9 "Classe segno opposto   "
-  FIELD LF_PCON->SEZIVDOPP
+  FIELD SEZIVDOPP
   GROUP 1 2 4 6
   ITEM "0|0. Nessuna" MESSAGE CLEAR,7@
   ITEM "1|1. Attivita'" MESSAGE ENABLE,7@
@@ -276,39 +275,38 @@ END
 
 STRING FLD_CM1_LETTIVDOPP 1
 BEGIN
-  PROMPT 57 9 ""
+  PROMPT 55 9 ""
   HELP "Codice del conto di sezione opposta secondo la IV direttiva CEE"
-  FIELD LF_PCON->LETTIVDOPP
+  FIELD LETTIVDOPP
   FLAGS "U"
   GROUP 1 2 4 7
 END
 
 NUMBER FLD_CM1_NUMRIVDOPP 8 4
 BEGIN
-  PROMPT 61 9 ""
+  PROMPT 59 9 ""
   HELP "Codice del conto di sezione opposta secondo la IV direttiva CEE"
-  FIELD LF_PCON->NUMRIVDOPP
+  FIELD NUMRIVDOPP
   FLAGS "MZ"
   GROUP 1 2 4 7
 END
 
-NUMBER FLD_CM1_NUMIVDOPP 2
+STRING FLD_CM1_NUMIVDOPP 4
 BEGIN
-  PROMPT 72 9 ""
+  PROMPT 70 9 ""
   HELP "Codice del conto di sezione opposta secondo la IV direttiva CEE"
-  FIELD LF_PCON->NUMIVDOPP
-  FLAGS "Z"
+  FIELD NUMIVDOPP
   GROUP 1 2 4 7
   COPY USE FLD_CM1_NUMIVD
   INPUT CODTAB[1,1] FLD_CM1_SEZIVDOPP
   INPUT CODTAB[2,2] FLD_CM1_LETTIVDOPP
   INPUT CODTAB[3,6] FLD_CM1_NUMRIVDOPP
-  INPUT CODTAB[7,8] FLD_CM1_NUMIVDOPP
+  INPUT CODTAB[7,10] FLD_CM1_NUMIVDOPP
   COPY DISPLAY FLD_CM1_NUMIVD
   OUTPUT FLD_CM1_SEZIVDOPP CODTAB[1,1]
   OUTPUT FLD_CM1_LETTIVDOPP CODTAB[2,2]
   OUTPUT FLD_CM1_NUMRIVDOPP CODTAB[3,6]
-  OUTPUT FLD_CM1_NUMIVDOPP CODTAB[7,8]
+  OUTPUT FLD_CM1_NUMIVDOPP CODTAB[7,10]
   OUTPUT FLD_CM1_DESCIVDOPP S0
   CHECKTYPE NORMAL
   WARNING "Codice non presente"
@@ -324,7 +322,7 @@ BEGIN
   DISPLAY "Sezione" CODTAB[1,1]
   DISPLAY "Lettera" CODTAB[2,2]
   DISPLAY "Classe  @M" CODTAB[3,6]
-  DISPLAY "Numero" CODTAB[7,8]
+  DISPLAY "Numero" CODTAB[7,10]
   COPY OUTPUT FLD_CM1_NUMIVDOPP
   CHECKTYPE NORMAL
 END
@@ -332,7 +330,7 @@ END
 LIST FLD_CM1_TIPOSPRIC 1 50
 BEGIN
   PROMPT 1 11 "Tipo Spesa/Ricavo      "
-  FIELD LF_PCON->TIPOSPRIC
+  FIELD TIPOSPRIC
   GROUP 1 2
   HELP "Specificare il tipo do conto"
   ITEM "0|0. Acquisti o vendite in genere"
@@ -393,7 +391,7 @@ END
 LIST FLD_CM1_TMCF 1 13
 BEGIN
   PROMPT 1 13 "Tipo sottoconti           "
-  FIELD LF_PCON->TMCF
+  FIELD TMCF
   GROUP 1 3
   HELP "Tipo dei sottoconti (Normale o clienti/fornitori)"
   ITEM " |Normali"
@@ -405,7 +403,7 @@ LIST FLD_CM2_SEZSALDI 1 10
 BEGIN
   PROMPT 1 14 "Controllo saldo primanota "
   HELP "Tipo di controllo del saldo in prima nota"
-  FIELD LF_PCON->SEZSALDI
+  FIELD SEZSALDI
   GROUP 1
   ITEM " |Nessuno"
   ITEM "A|Avere"
@@ -416,7 +414,7 @@ BOOLEAN FLD_CM2_STSOTTBIL
 BEGIN
   PROMPT 1 15 "Non stampare dett.sottoc. su bilanci a sezioni"
   HELP "Indicare se stampare il dettaglio dei sottoconti nei bilanci a sezioni contrapposte"
-  FIELD LF_PCON->STSOTTBIL
+  FIELD STSOTTBIL
   GROUP 1 3
 END
 
@@ -424,7 +422,7 @@ BOOLEAN FLD_CM2_COMPENS
 BEGIN
   PROMPT 56 15 "Compensazione saldi"
   HELP "Indicare se e' ammessa la compensazione dei saldi"
-  FIELD LF_PCON->COMPENS
+  FIELD COMPENS
   GROUP 1 3
 END
 
@@ -432,7 +430,7 @@ BOOLEAN FLD_CM2_STSOTTAB
 BEGIN
   PROMPT 1 16 "Stampa dettaglio sottoconti su analisi"
   HELP "Indicare se stampare il dettaglio dei sottoconti nell'analisi di bilancio"
-  FIELD LF_PCON->STSOTTAB
+  FIELD STSOTTAB
 //  FLAGS "H"
   GROUP 1 3
   MESSAGE COPY,FLD_CM2_STSOTTABS
@@ -441,7 +439,7 @@ END
 BOOLEAN FLD_CM2_STSOTTABS
 BEGIN
   PROMPT 1 16 "Stampa dettaglio movimenti su analisi  "
-  FIELD LF_PCON->STSOTTAB
+  FIELD STSOTTAB
 //  FLAGS "H"
   GROUP 1 2
   MESSAGE COPY,FLD_CM2_STSOTTAB
@@ -451,7 +449,7 @@ BOOLEAN FLD_CM2_SOSPESO
 BEGIN
   PROMPT 56 16 "Conto sospeso"
   HELP "Indicare se sospendere il conto in prima nota"
-  FIELD LF_PCON->SOSPESO
+  FIELD SOSPESO
   GROUP 1 2
 END
 
diff --git a/cg/cg1100.cpp b/cg/cg1100.cpp
index 16911aae2..b1de03d04 100755
--- a/cg/cg1100.cpp
+++ b/cg/cg1100.cpp
@@ -6,6 +6,7 @@
 #include <mask.h>
 #include <printapp.h>
 #include <sort.h>
+#include <recarray.h>
 #include <tabutil.h>
 #include <utility.h>
 #include <progind.h>
@@ -16,11 +17,8 @@
 #include "cg1.h"
 #include "cg1100.h"
 
-const char * TAB_ANABIL = "%IVD";
 const char * TAB_IVD = "%IVD";
 
-const int CODTABLEN = 15;
-
 enum stampe {
   completa=1,
   con_IV_direttiva,
@@ -30,8 +28,6 @@ enum stampe {
   senza_ana_bil
   };
 
-/* modifica inutile per provare cvs remoto */
-
 class CG1100_application : public TPrintapp
 {                                              
   struct bil_ivd
@@ -39,7 +35,7 @@ class CG1100_application : public TPrintapp
     char   sez;
     char   let;
     char   numr[5];
-    char   num[4];
+    char   num[5];
     char   gruppo[4];
     char   conto[4];
     char   sottoc[8];
@@ -47,37 +43,32 @@ class CG1100_application : public TPrintapp
     char   sez_opp;
     char   let_opp;
     char   numr_opp[5];
-    int    num_opp;
+    char   num_opp[5];
   };
   
   bil_ivd*            _bil;
-  TTable*             _tab;           // tabella codici IV direttiva
-  TIsamtempfile*      _tpcon;
-  TLocalisamfile*     _pcon;
   TRectype*           _rec;
   TSort*              _sort;
-  TRelation*          _rel, *_relt;
+  TRelation *         _rel;
   TMask*              _msk;           
   const char*         _buf;
   stampe              _tipo_stampa;
   bool                _salto_pag,_resetta_righe_stampa;
   int                 _old_gruppo;
-  int                 _pcont_reclen,_i;
-  int                 _cur_c1, _cur_c2, _cur_c3;
+  int                 _i;
+  int                 _cur_c1, _cur_c2;
   TString             _clivd, _clivdo;  
-  TParagraph_string   _d1, _d2;            // qui
+  TParagraph_string   _d1, _d2, _d3;
   char                _sez_da_stamp,_sez_stamp,_let_da_stamp,_let_stamp;
-  TString             _numr_da_stamp,_numr_stamp;
-  int                 _gruppo,_conto,_num_da_stamp,_num_stamp,_g_prec,_c_prec;
+  TString             _numr_da_stamp,_numr_stamp, _num_stamp, _num_da_stamp;
+  int                 _gruppo,_conto, _g_prec,_c_prec;
   long                _sottoc,_s_prec;
   TString             _classe_da_stampare,_classe_stampata,_codcbl_da_stamp,_codcbl_stamp; 
   bool                _conto_classificato,_stampa_riga_vuota;
   int                 _sottoc_classificato;
-  bool                _prima_volta, _stampa_g, _stampa_c;
+  bool                _prima_volta;
   TDate               _data_stampa;
 
-  TString tmp;        // Stringa per porcate galattiche
-  
 public:
 
   virtual bool user_destroy() ;
@@ -87,7 +78,6 @@ public:
   virtual bool preprocess_print (int,int);
   virtual bool preprocess_page (int,int);
   virtual print_action postprocess_page (int,int);  
-  virtual void postclose_print ();
 
   virtual bool set_print(int);
 
@@ -99,24 +89,20 @@ public:
   void set_con_IV ();
   void set_senza_IV_ana ();
   void set_con_ana ();
-//  void set_senza_ana ();       
-  void prepara_pcon_temp();
-  void cancella(int,int,long);
   void init_sort();
-  const char* descrizione_numero(char, char, int, int);
-  const char* descrizione_codcbl(TString&);
-  // void setta_righe_descr(TParagraph_string*);
+  const TString & descrizione_numero(char, char, int, const char *);
+  const TString & descrizione_codcbl(const TString &);
   int  leggo_sottoc(int,int,long);
-  void riempi_record(char,char,const TString&,int,int,int,long,const TString&,char,char,const TString&,int);
+  void riempi_record(char,char,const TString&, const TString &,int,int,long,const TString&,char,char,const TString&, const TString &);
   void set_bil_key(bil_ivd* b, char sezione, char lettera,
-                   const char* numero_romano, int numero,
+                   const char* numero_romano, const char * numero,
                    int gruppo = 0, int conto = 0, long sottoconto = 0L);
   void set_bil_val(bil_ivd* b, const char* descr,char sez_opp,char let_opp,
-                   const char* numr_opp,int num_opp);
+                   const char* numr_opp, const char * num_opp);
 
   virtual bool process_link(int id, const char* txt);
 
-  CG1100_application() : _clivd(8), _clivdo(8), _d1("", 30), _d2("", 40) {}
+  CG1100_application() : _clivd(8), _clivdo(8), _d1("", 30), _d2("", 40), _d3("", 40) {}
 };
 
 bool CG1100_application::process_link(int id, const char* txt)
@@ -139,7 +125,7 @@ void CG1100_application::init_sort()
     _sort -> addsortkey ((char*)&(_bil->sez)    - (char*)&(_bil->sez),1);
     _sort -> addsortkey ((char*)&(_bil->let)    - (char*)&(_bil->sez),1);
     _sort -> addsortkey ((char*)&(_bil->numr)   - (char*)&(_bil->sez),4);
-    _sort -> addsortkey ((char*)&(_bil->num)    - (char*)&(_bil->sez),2);
+    _sort -> addsortkey ((char*)&(_bil->num)    - (char*)&(_bil->sez),4);
     _sort -> addsortkey ((char*)&(_bil->gruppo) - (char*)&(_bil->sez),3);
     _sort -> addsortkey ((char*)&(_bil->conto)  - (char*)&(_bil->sez),3);
     _sort -> addsortkey ((char*)&(_bil->sottoc) - (char*)&(_bil->sez),6);
@@ -165,13 +151,13 @@ void CG1100_application::init_sort()
 }
 
 void CG1100_application::set_bil_key(bil_ivd* b, char sezione, char lettera,
-                                     const char* numero_romano, int numero,
+                                     const char* numero_romano, const char * numero,
                                      int gruppo, int conto,long sottoconto)
 {
   b->sez = sezione;
   b->let = lettera;
   strcpy(b->numr, numero_romano);
-  sprintf(b->num , "%2d", numero);
+  sprintf(b->num , "%-4s", numero);
   sprintf(b->gruppo , "%3d", gruppo);
   sprintf(b->conto , "%3d", conto);
   sprintf(b->sottoc , "%6ld", sottoconto);
@@ -179,34 +165,26 @@ void CG1100_application::set_bil_key(bil_ivd* b, char sezione, char lettera,
 
 void CG1100_application::set_bil_val(bil_ivd* b, const char* descr, 
                                      char sez_opp,char let_opp,
-                                     const char* numr_opp,int num_opp)
+                                     const char* numr_opp, const char * num_opp)
 {
   strcpy(b->descr, descr);
   b->sez_opp           = sez_opp;
   b->let_opp           = let_opp;
   strcpy(b->numr_opp, numr_opp);
-  b->num_opp           = num_opp;
+  strcpy(b->num_opp, num_opp);
 }
 
 void CG1100_application::riempi_record(char sez,char let,const TString& numr,
-                                       int numero,int g,int c,long s,
+                                       const TString & numero,int g,int c,long s,
                                        const TString& descr,char sez_opp,
                                        char let_opp,const TString& numr_opp,
-                                       int num_opp)
+                                       const TString& num_opp)
 {
   set_bil_key(_bil, sez, let, numr, numero, g, c, s);
   set_bil_val(_bil, descr, sez_opp, let_opp, numr_opp, num_opp);
   _sort->sort ((const char*) _bil);
 }
 
-void CG1100_application::postclose_print()
-{     
-  if (_tipo_stampa == senza_ana_bil)
-  {
-    delete _relt;
-  }
-}
-
 print_action CG1100_application::postprocess_page(int file,int counter)
 {    
   switch (_tipo_stampa)
@@ -224,7 +202,7 @@ print_action CG1100_application::postprocess_page(int file,int counter)
       _let_stamp  = _let_da_stamp;
       _numr_stamp = _numr_da_stamp;
       _num_stamp  = _num_da_stamp; 
-      _classe_stampata.format("%c%c%s%2d",_sez_stamp,_let_stamp,(const char*)_numr_stamp,_num_stamp);
+      _classe_stampata.format("%c%c%s%-4s",_sez_stamp,_let_stamp,(const char*)_numr_stamp, (const char *) _num_stamp);
     
       if ( (_buf = _sort->retrieve()) != NULL)
       { 
@@ -233,13 +211,11 @@ print_action CG1100_application::postprocess_page(int file,int counter)
         _let_da_stamp  = bil->let;
         _numr_da_stamp = bil->numr;
         _numr_da_stamp.ltrim();
-        _num_da_stamp  = atoi(bil->num);
+        _num_da_stamp  = bil->num;
         _gruppo        = atoi(bil->gruppo);
         _conto         = atoi(bil->conto);
         _sottoc        = atol(bil->sottoc); 
-        _classe_da_stampare.format("%c%c%s%2d",_sez_da_stamp,_let_da_stamp,(const char*)_numr_da_stamp,_num_da_stamp);
-      
-        //set_auto_ff(FALSE);
+        _classe_da_stampare.format("%c%c%s%-4s",_sez_da_stamp,_let_da_stamp,(const char*)_numr_da_stamp, (const char *) _num_da_stamp);
       
         return REPEAT_PAGE; 
       }
@@ -271,7 +247,6 @@ print_action CG1100_application::postprocess_page(int file,int counter)
 
 void CG1100_application::set_page(int file,int counter)
 {   
-  //intesta (_tipo_stampa);
   switch (_tipo_stampa) 
   {
     case con_IV_direttiva: 
@@ -317,9 +292,9 @@ void CG1100_application::do_sort()
   if (_tipo_stampa == con_IV_direttiva)
   {
     char    sez_conto,let_conto;
-    TString numr_conto;
-    int     num_conto;
-    bool    classe_conto = FALSE;
+    TString16    numr_conto;
+    TString16    num_conto;
+    bool    classe_conto = false;
     
     _sort->init();
     select_cursor (_cur_c1);
@@ -329,7 +304,7 @@ void CG1100_application::do_sort()
 
     long last =  cursor->items();   
     
-    TProgind prg (last, TR("Elaborazione Piano dei Conti... Prego attendere"), FALSE, TRUE, 30);
+    TProgind prg (last, TR("Elaborazione Piano dei Conti... Prego attendere"), false, true, 30);
 
     for ( *cursor = 0; cursor->pos() < last; ++(*cursor) )
     {
@@ -343,13 +318,13 @@ void CG1100_application::do_sort()
 
       char    sez      = rec.get_char(PCN_SEZIVD);       
       char    let      = rec.get_char(PCN_LETTIVD); 
-      TString numr     = rec.get     (PCN_NUMRIVD);
-      int     num      = rec.get_int (PCN_NUMIVD); 
+      const TString16 numr     = rec.get     (PCN_NUMRIVD);
+      const TString16 num      = rec.get     (PCN_NUMIVD); 
       TString descr    = rec.get     (PCN_DESCR);
       char    sez_opp  = rec.get_char(PCN_SEZIVDOPP);
       char    let_opp  = rec.get_char(PCN_LETTIVDOPP);
-      TString numr_opp = rec.get     (PCN_NUMRIVDOPP);
-      int     num_opp  = rec.get_int (PCN_NUMIVDOPP);       
+      const TString16 numr_opp = rec.get     (PCN_NUMRIVDOPP);
+      const TString16 num_opp  = rec.get     (PCN_NUMIVDOPP);       
       
       if ((g != 0) && (c != 0) && (s == 0))
       {
@@ -367,11 +342,11 @@ void CG1100_application::do_sort()
           
           numr_conto   = numr;
           num_conto    = num;
-          classe_conto = TRUE;  
+          classe_conto = true;  
           riempi_record(sez_conto,let_conto,numr_conto,num_conto,g,c,s,descr,sez_opp,let_opp,numr_opp,num_opp);
         }
         else
-          classe_conto      = FALSE; 
+          classe_conto      = false; 
       }
       
       if ((g != 0) && (c != 0) && (s != 0))
@@ -398,7 +373,7 @@ void CG1100_application::do_sort()
   
   if (_tipo_stampa == con_ana_bil)
   {        
-    bool livello_conto = FALSE;
+    bool livello_conto = false;
        
     _sort->init();
 
@@ -409,7 +384,7 @@ void CG1100_application::do_sort()
 
     long last =  cursor->items();
     
-    TProgind prg (last, TR("Elaborazione Piano dei Conti... Prego attendere"), FALSE, TRUE, 30);
+    TProgind prg (last, TR("Elaborazione Piano dei Conti... Prego attendere"), false, true, 30);
     
     TString c1(12);
     
@@ -419,14 +394,13 @@ void CG1100_application::do_sort()
     { 
       prg.addstatus(1);
                                   
- //     int  gruppo = rec.get_int (PCN_GRUPPO);
       int  conto  = rec.get_int (PCN_CONTO);
       long sottoc = rec.get_long(PCN_SOTTOCONTO);
       
       if (livello_conto && (conto != conto_p) )
       {
         c1 = "";
-        livello_conto = FALSE;
+        livello_conto = false;
       }
         
       conto_p = conto;
@@ -441,7 +415,7 @@ void CG1100_application::do_sort()
           else
           {
             c1 = rec.get(PCN_CODCBL);
-            livello_conto = TRUE;
+            livello_conto = true;
           }
         }
         else                         // Si tratta di un sottoconto
@@ -457,108 +431,6 @@ void CG1100_application::do_sort()
   }
 }
 
-void CG1100_application::cancella(int g, int c, long s)
-{
-  _tpcon->setkey(1);
-  _tpcon->zero();
-  _tpcon->put(PCN_GRUPPO,     g);
-  _tpcon->put(PCN_CONTO,      c);
-  _tpcon->put(PCN_SOTTOCONTO, s);
-  if (_tpcon->read() == NOERR)
-    _tpcon->remove();
-}
-
-void CG1100_application::prepara_pcon_temp()
-{
-  TLocalisamfile pcon (LF_PCON);
-  TRectype       rec  (LF_PCON);
-  bool gruppo_riclassificato = FALSE;
-  bool conto_riclassificato  = FALSE;
-  
-  int g_prec = -1;
-  int c_prec = -1;      
-  
-  long items = pcon.items();
-  
-  TProgind prog (items,TR("Elaborazione Piano dei Conti... Prego attendere"), FALSE, TRUE, 30);
-  
-  for (pcon.first(); !pcon.eof(); pcon.next())
-  {
-    prog.addstatus(1);
-    
-    int  g = pcon.get_int (PCN_GRUPPO);
-    int  c = pcon.get_int (PCN_CONTO);
-    long s = pcon.get_long(PCN_SOTTOCONTO);
-    
-    if (gruppo_riclassificato && g == g_prec) 
-      continue;
-    else
-      gruppo_riclassificato = FALSE;
-    
-    if (conto_riclassificato && (g == g_prec && c == c_prec) )
-      continue;
-    else
-      conto_riclassificato = FALSE;
-    
-    TString16 codcbl = pcon.get(PCN_CODCBL);
-    
-    if (c == 0)      // Se si tratta di un gruppo    
-    {
-      if (codcbl.empty())
-      {
-        rec = pcon.curr();
-        
-        _tpcon->zero();
-        _tpcon->curr() = rec;
-        _tpcon->write();
-      }  
-      else
-        gruppo_riclassificato = TRUE;
-    }
-    else
-      if (s == 0)    // Se si tratta di un conto
-      {
-        if (codcbl.empty())
-        {
-          rec = pcon.curr();
-          
-          _tpcon->zero();
-          _tpcon->curr() = rec;
-          _tpcon->write();
-        }                
-        else 
-        {
-          int gruppo = pcon.get_int(PCN_GRUPPO);
-          
-          cancella(gruppo,0,0);   // Cancella l'eventuale gruppo
-          
-          conto_riclassificato = TRUE;
-        }
-      }
-      else           // Se si tratta di un sottoconto
-      {
-        if (codcbl.empty())
-        {
-          rec = pcon.curr();
-          
-          _tpcon->zero();
-          _tpcon->curr() = rec;
-          _tpcon->write();
-        }                
-        else 
-        {
-          int gruppo = pcon.get_int(PCN_GRUPPO);
-          int conto  = pcon.get_int(PCN_CONTO);
-          
-          cancella(gruppo,0,0);      // Cancella l'eventuale gruppo
-          cancella(gruppo,conto,0);  // Cancella l'eventuale conto
-        }
-      }
-  }
-  select_cursor(_cur_c3);  // Seleziono il cursore definito sul piano dei conti temporaneo
-  _tpcon->first();
-}
-
 bool CG1100_application::preprocess_print (int file,int counter)
 {
   switch (_tipo_stampa)
@@ -578,16 +450,16 @@ bool CG1100_application::preprocess_print (int file,int counter)
         _let_da_stamp  = bil->let;
         _numr_da_stamp = bil->numr;
         _numr_da_stamp.ltrim();
-        _num_da_stamp  = atoi(bil->num);
+        _num_da_stamp  = bil->num;
         _gruppo        = atoi(bil->gruppo);
         _conto         = atoi(bil->conto);
         _sottoc        = atol(bil->sottoc); 
-        _classe_da_stampare.format("%c%c%s%2d",_sez_da_stamp,_let_da_stamp,(const char*)_numr_da_stamp,_num_da_stamp);
+        _classe_da_stampare.format("%c%c%s%-4s",_sez_da_stamp,_let_da_stamp,(const char*)_numr_da_stamp, (const char *)_num_da_stamp);
       
-        return TRUE;
+        return true;
       }
       else
-        return FALSE; 
+        return false; 
     }
     break;
     case con_ana_bil: 
@@ -602,10 +474,10 @@ bool CG1100_application::preprocess_print (int file,int counter)
         _conto            = rec.get_int(PCN_CONTO);
         _sottoc           = rec.get_long(PCN_SOTTOCONTO); 
       
-        return TRUE;
+        return true;
       }
       else
-        return FALSE;
+        return false;
     }        
     break;    
     case senza_ana_bil:
@@ -613,7 +485,7 @@ bool CG1100_application::preprocess_print (int file,int counter)
     default:
     break;
   }
-  return TRUE;
+  return true;
 }
 
 void CG1100_application::set_con_IV()
@@ -622,18 +494,18 @@ void CG1100_application::set_con_IV()
   
   TString descrizione,descr;
   char    sez_opp,let_opp;
-  int     num_opp,numr_opp;
-  bool stampa_classe = TRUE;    
+  int     numr_opp;
+  bool stampa_classe = true;    
   int     numr       = atoi(_numr_da_stamp);
   TString numrom     = itor(numr); 
+  TString num_opp(bil->num_opp);
   
   sez_opp  = bil->sez_opp;
   let_opp  = bil->let_opp;
   numr_opp = atoi(bil->numr_opp);
   TString  numrom_opp = itor(numr_opp);
-  num_opp  = bil->num_opp;
   
-  descrizione  = descrizione_numero(_sez_da_stamp,_let_da_stamp,numr,_num_da_stamp);
+  descrizione  = descrizione_numero(_sez_da_stamp,_let_da_stamp,numr, _num_da_stamp);
   descr    = bil->descr;
   
   //Se la classe prelevata dal record corrente del sort e' diversa dalla classe
@@ -650,7 +522,7 @@ void CG1100_application::set_con_IV()
         set_row (_i++,"@0g%c", app);   
         set_row (_i++,FR("@0gCONTI D' ORDINE ATTIVI"));
         set_row (_i++,"@0g%c", app);
-        stampa_classe = FALSE;
+        stampa_classe = false;
       } 
       else
         if ((_sez_da_stamp == '1')&&(_let_da_stamp != 'Z'))
@@ -667,7 +539,7 @@ void CG1100_application::set_con_IV()
         set_row(_i++,"@0g%c", app); 
         set_row (_i++,FR("@0gCONTI D' ORDINE PASSIVI"));
         set_row(_i++,"@0g%c", app); 
-        stampa_classe = FALSE;
+        stampa_classe = false;
       } 
       else
         if ((_sez_da_stamp == '2')&&(_let_da_stamp != 'Z'))
@@ -684,7 +556,7 @@ void CG1100_application::set_con_IV()
         set_row(_i++,"@0g%c", app); 
         set_row (_i++,FR("@0gCONTI D' ORDINE"));
         set_row(_i++,"@0g%c", app); 
-        stampa_classe = FALSE;
+        stampa_classe = false;
       }                                  
       
       if (_sez_da_stamp == '9')
@@ -704,7 +576,7 @@ void CG1100_application::set_con_IV()
           set_row (_i++,"@0g%c", app);   
           set_row (_i++,FR("@0gCONTI D' ORDINE ATTIVI"));
           set_row (_i++,"@0g%c", app);
-          stampa_classe = FALSE;
+          stampa_classe = false;
         }
         if ((_sez_da_stamp == '2')&&(_let_da_stamp == 'Z'))
         {
@@ -712,7 +584,7 @@ void CG1100_application::set_con_IV()
           set_row(_i++,"@0g%c", app); 
           set_row (_i++,FR("@0gCONTI D' ORDINE PASSIVI"));
           set_row(_i++,"@0g%c", app); 
-          stampa_classe = FALSE;
+          stampa_classe = false;
         }
       }
     
@@ -728,12 +600,10 @@ void CG1100_application::set_con_IV()
         if (_numr_da_stamp != "")
           set_row(_i,"@2g%8s", (const char*) numrom);
 
-        if (_num_da_stamp != 0)
-          set_row(_i,"@11g%2d", _num_da_stamp);   
+        set_row(_i,"@11g%-4s", (const char *)_num_da_stamp);   
         
-        _d2 = (const char*) descrizione;
-        set_row(_i,"@14g#a", &_d2);   
-        //    setta_righe_descr(_descr);
+        _d2 = descrizione;
+        set_row(_i,"@16g#a", &_d2);   
       }
     }  
   }                                            
@@ -753,8 +623,8 @@ void CG1100_application::set_con_IV()
     if (numr_opp != 0)
       set_row (_i,"@120g%8s", (const char*) numrom_opp);
     
-    if (num_opp != 0)
-      set_row (_i++,"@129g%2d", num_opp);
+    if (num_opp.not_empty())
+      set_row (_i++,"@129g%-4s", num_opp);
   }
   else
     _i++;
@@ -777,25 +647,24 @@ void CG1100_application::set_senza_IV_ana()
   {
     _g_prec = gruppo;
     _c_prec = conto;
-    _prima_volta = FALSE;
+    _prima_volta = false;
   }
   
   if (sottoc == 0L) // Se si tratta di un conto  
   {
     if (gruppo != _g_prec)
-      _stampa_riga_vuota = TRUE;
+      _stampa_riga_vuota = true;
   }
   else
   {   
     if (gruppo != _g_prec || conto != _c_prec)
-      _stampa_riga_vuota = TRUE;
+      _stampa_riga_vuota = true;
   }
 
   if (_stampa_riga_vuota)
   {                            
-    char app = ' ';
-    set_row (i++,"@0g%c", app);
-    _stampa_riga_vuota = FALSE;
+    i++;
+    _stampa_riga_vuota = false;
   }
   
   set_row (i, "$[b]@pn$[n] $[b]@pn$[n] $[b]@pn$[n]",
@@ -831,11 +700,7 @@ void CG1100_application::set_con_ana()
   
   rec = _buf;
   
-  TString descrizione,descr;
-//  bool stampa_codcbl = TRUE;    
-  
   TString codcbl = rec.get(PCN_CODCBL);
- // int     gruppo = rec.get_int (PCN_GRUPPO);
   int     conto  = rec.get_int (PCN_CONTO);
   long    sottoc = rec.get_long(PCN_SOTTOCONTO);
   bool    stsobi = rec.get_bool(PCN_STSOTTAB);
@@ -844,16 +709,11 @@ void CG1100_application::set_con_ana()
   else
     val = TR("No");
   
-  descrizione  = descrizione_codcbl(codcbl);
-  descr        = rec.get(PCN_DESCR);
-
-  char app = ' ';
-  set_row (_i++,"@0g%c", app);
-  
   if (_codcbl_da_stamp != _codcbl_stamp)
   {
-    set_row (_i,"@0g%10s", (const char*) _codcbl_da_stamp);
-    set_row (_i,"@11g%s",  (const char*) descrizione);   
+    set_row (_i,"@0g%s", (const char*) _codcbl_da_stamp);
+		_d3 = descrizione_codcbl(codcbl);
+    set_row (_i,"@13g#a", &_d3);   
   }                                            
 
   set_row (_i,"@62g$[b]%3d$[n]", _gruppo);
@@ -867,7 +727,7 @@ void CG1100_application::set_con_ana()
   if (_gruppo > 99 || _conto > 99)
     set_row(_i,"@76g*");
       
-  set_row (_i,"@78g%.40s", (const char*) descr); 
+  set_row (_i,"@78g%.40s", (const char*) rec.get(PCN_DESCR)); 
 
   if (conto != 0 && sottoc == 0l)
     set_row (_i, "@121g%s", (const char*) val);
@@ -884,7 +744,6 @@ void CG1100_application::set_completa()
   char       sezione;
   int        i;
   
-//  int  gruppo = rec.get_int (PCN_GRUPPO);
   int  conto  = rec.get_int (PCN_CONTO);
   long sottoc = rec.get_long(PCN_SOTTOCONTO);      
   sezione     = rec.get_char(PCN_SEZIVD);    
@@ -893,7 +752,7 @@ void CG1100_application::set_completa()
   if (_prima_volta)      
   {
     _s_prec = 0;
-    _prima_volta = FALSE;
+    _prima_volta = false;
   }
   
   if (sottoc != 0l && _s_prec != 0l)                                      
@@ -924,7 +783,7 @@ void CG1100_application::set_completa()
   }
   else
     if (_tipo_stampa == completa_bil)
-      set_row (i, "@60g@10s", FLD(LF_PCON, PCN_CODCBL) );
+      set_row (i, "@60g@12s", FLD(LF_PCON, PCN_CODCBL) );
   
   if (conto != 0 && sottoc == 0l)
   {
@@ -990,8 +849,8 @@ bool CG1100_application::elabora_riga()
   }
 
   // Gestione salto pagina
-  if (_tipo_stampa == con_ana_bil) // || _tipo_stampa == con_IV_direttiva)
-    return FALSE;
+  if (_tipo_stampa == con_ana_bil)
+    return false;
 
   int new_gruppo = curr_rec.get_int(PCN_GRUPPO);
 
@@ -1001,7 +860,7 @@ bool CG1100_application::elabora_riga()
     _old_gruppo = new_gruppo;
     return salta;
   }
-  return FALSE;
+  return false;
 }
 
 int CG1100_application::leggo_sottoc(int gruppo,int conto,long sottoc)
@@ -1010,8 +869,8 @@ int CG1100_application::leggo_sottoc(int gruppo,int conto,long sottoc)
   char sez;
   int  gr,co;
   int  esito = 0;
-  bool esiste_conto_classificato     = FALSE;
-  bool esiste_conto_non_classificato = FALSE;
+  bool esiste_conto_classificato     = false;
+  bool esiste_conto_non_classificato = false;
   
   pconti.zero();
   pconti.put(PCN_GRUPPO,     gruppo);
@@ -1028,10 +887,10 @@ int CG1100_application::leggo_sottoc(int gruppo,int conto,long sottoc)
     sez = pconti.get_char(PCN_SEZIVD);
     
     if (sez != '0') 
-      esiste_conto_classificato = TRUE;
+      esiste_conto_classificato = true;
     
     if (sez == '0')
-      esiste_conto_non_classificato = TRUE;              
+      esiste_conto_non_classificato = true;              
   }
   
   if (!esiste_conto_classificato && esiste_conto_non_classificato)
@@ -1048,7 +907,6 @@ int CG1100_application::leggo_sottoc(int gruppo,int conto,long sottoc)
 
 bool CG1100_application::preprocess_page(int file,int counter)
 {
-//  static int c1 = 0;
   static TString16 a1;
   char   sez;
   TString16 codcbl;                                   
@@ -1067,7 +925,7 @@ bool CG1100_application::preprocess_page(int file,int counter)
       
       force_setpage();
       
-      if (conto == 0) return FALSE; //Scarto i gruppi
+      if (conto == 0) return false; //Scarto i gruppi
        
       if (sottoc == 0L) // Se si tratta di un conto
       { 
@@ -1077,24 +935,24 @@ bool CG1100_application::preprocess_page(int file,int counter)
         {                           
           _sottoc_classificato = byte(leggo_sottoc(gruppo,conto,sottoc));  
           if (_sottoc_classificato == 0)
-            _conto_classificato = TRUE;
+            _conto_classificato = true;
           else
             if (_sottoc_classificato == 1)
             {  
-              _conto_classificato  = FALSE;
-              return FALSE;
+              _conto_classificato  = false;
+              return false;
             }   
             else
               if (_sottoc_classificato == 2)
               {
-                _conto_classificato = TRUE;
-                return FALSE;
+                _conto_classificato = true;
+                return false;
               }
         }
         else                        
         {
-          _conto_classificato = TRUE;
-          return FALSE;                
+          _conto_classificato = true;
+          return false;                
         }
       }
       else                              // Se si tratta di un sottoconto
@@ -1104,10 +962,10 @@ bool CG1100_application::preprocess_page(int file,int counter)
           char sezione = rec.get_char(PCN_SEZIVD);
           
           if (sezione != '0')
-            return FALSE;
+            return false;
         }
         else
-          return FALSE;    
+          return false;    
       }
       _g_prec = gruppo;
       _c_prec = conto; 
@@ -1125,44 +983,12 @@ bool CG1100_application::preprocess_page(int file,int counter)
       
       force_setpage();
 
-      if (gruppo != _g_prec)
-      {
-        _stampa_g = TRUE; 
-        _stampa_c = TRUE;
-      }
-        
-      if ( (gruppo != _g_prec || conto != _c_prec) && _stampa_g)
-        _stampa_c = TRUE;
    
       _g_prec = gruppo;  
       _c_prec = conto;
       
-      if (conto == 0)      // Si tratta di un gruppo
-      {
-        _stampa_g = FALSE;
-        _stampa_c = FALSE;
-        return TRUE;
-      }
-      
-      if (sottoc == 0)     // Si tratta di un conto
-      { 
-        if (_stampa_g)
-        {
-          _stampa_c = FALSE;
-          return TRUE;
-        }
-        else
-          return FALSE;
-      }             
-        
-      if (sottoc != 0)     // Si tratta di un sottoconto
-      {
-        if (_stampa_c)
-          return TRUE;
-        else
-          return FALSE;
-      }
     }
+    return true;
   }    
 
   if (elabora_riga())
@@ -1174,7 +1000,7 @@ bool CG1100_application::preprocess_page(int file,int counter)
   _clivd = itor(c3);
   _clivdo = itor(o3);
 
-  return TRUE;
+  return true;
 }
 
 bool CG1100_application::set_print(int)
@@ -1186,21 +1012,22 @@ bool CG1100_application::set_print(int)
 
   if (tasto == K_ENTER)
   {
-    _tipo_stampa = (stampe)_msk->get_int(F_SCELTA_STAMPA);
+    select_cursor(_cur_c1);
+    current_cursor()->setfilter("");
+		_tipo_stampa = (stampe)_msk->get_int(F_SCELTA_STAMPA);
     _salto_pag   = _msk->get_bool(F_SALTO_PAGINA);
     _data_stampa = _msk->get(F_DATA_STAMPA);
 
-    // scegli_cur();
     enable_link(TR("Collegamento Piano dei conti: "), 'b');
-    set_multiple_link(TRUE);
+    set_multiple_link(true);
     
     _sez_stamp  = ' ';
     _let_stamp  = ' ';
     _numr_stamp = "";
-    _num_stamp  = 0; 
+    _num_stamp  = ""; 
     _classe_stampata = "";               
     
-    _resetta_righe_stampa = TRUE;
+    _resetta_righe_stampa = true;
     
     reset_footer();
     if (_tipo_stampa == con_ana_bil)
@@ -1210,10 +1037,10 @@ bool CG1100_application::set_print(int)
           
     if (_tipo_stampa == senza_IV_direttiva)
     {
-      _conto_classificato  = TRUE;
+      _conto_classificato  = true;
       _sottoc_classificato = 0;
-      _stampa_riga_vuota = FALSE;
-      _prima_volta = TRUE;  
+      _stampa_riga_vuota = false;
+      _prima_volta = true;  
     }
     
     switch (_tipo_stampa) 
@@ -1225,14 +1052,7 @@ bool CG1100_application::set_print(int)
       break;
     case senza_ana_bil: 
     { 
-      _tpcon = new TIsamtempfile (LF_PCON, "ab", TRUE);
-      _relt  = new TRelation (_tpcon);
-      TCursor *tcursor = new TCursor (_relt);
-  
-      _cur_c3 = add_cursor (tcursor);
- 
-      select_cursor(_cur_c1);
-      prepara_pcon_temp(); 
+      current_cursor()->setfilter("CODCBL==\"\"");
       break;
     }
     case con_IV_direttiva:
@@ -1243,15 +1063,14 @@ bool CG1100_application::set_print(int)
     default:
       break;
     }
-    //init_sort();
     
     intesta (_tipo_stampa);
     
     printer().footerlen(5);
     
-    return TRUE;
+    return true;
   }
-  return FALSE;
+  return false;
 }
 
 void CG1100_application::intesta (stampe tipo)
@@ -1290,7 +1109,7 @@ void CG1100_application::intesta (stampe tipo)
     s.fill('-');
     set_header (soh++, (const char *) s);
     set_header (soh++, FR("@58gCodici Piano@116gSez. e Classe"));
-    set_header (soh++, FR("Classe@14gDescrizione@58gdei Conti @73gDescrizione@116gdi segno opposto"));
+    set_header (soh++, FR("Classe@16gDescrizione@58gdei Conti @73gDescrizione@116gdi segno opposto"));
 
     break;
 
@@ -1315,7 +1134,7 @@ void CG1100_application::intesta (stampe tipo)
     s.fill('-');
     set_header (soh++, (const char *) s);
     set_header (soh++, FR("Codice @62gCodici Piano@118gDet.alleg.bil."));
-    set_header (soh++, FR("Tabella@11gDescrizione@62gdei Conti @78gDescrizione@118gSot.con * Mov."));
+    set_header (soh++, FR("Tabella@13gDescrizione@62gdei Conti @78gDescrizione@118gSot.con * Mov."));
     break;
 
   case senza_ana_bil:
@@ -1335,94 +1154,56 @@ void CG1100_application::intesta (stampe tipo)
 
 }
 
-const char* CG1100_application::descrizione_numero(char sezione, char lettera, int numr, int numero)
+const TString & CG1100_application::descrizione_numero(char sezione, char lettera, int numr, const char * numero)
 {
-  TTable& tabivd = *_tab;
-  TString dep,dep2;
+  TString key;
 
-  tabivd.zero();   
-  if (numr == 0 && numero == 0)
-    dep = format("%c%c",sezione,lettera);
-  else                        
-    if (numero == 0)
-    {
-      if (numr != 0)
-        dep = format("%1c%1c%04d",sezione, lettera, numr);
-      else
-        dep = format("%c%c    ",sezione,lettera);
-    }
-    else                                         
-    {
-      if (numr != 0)
-        dep = format("%1c%1c%04d%02d",sezione, lettera, numr,numero);
-      else
-        dep = format("%c%c    %02d",sezione,lettera,numero);
-    }
-  
-  tabivd.put("CODTAB", dep);
-  tabivd.read();   
-  dep2 = tabivd.get("CODTAB");
-  if (dep == dep2)
-    tmp = tabivd.get("S0");
-  else
-    tmp = "";
-  return tmp;
+  if (numr == 0)
+		key.format("%c%c    %-4s",sezione, lettera, numero);
+	else
+		key.format("%1c%1c%04d%-4s",sezione, lettera, numr, numero);
+	key.trim();
+
+  const TRectype & ivd = cache().get(TAB_IVD, key);
+
+  return ivd.get("S0");
 }     
 
-const char* CG1100_application::descrizione_codcbl(TString& codcbl)
+const TString & CG1100_application::descrizione_codcbl(const TString& codcbl)
 {
-  TLocalisamfile abpcon (LF_ABPCON);
+  const TRectype & abpcon = cache().get(LF_ABPCON, codcbl);
 
-  abpcon.setkey(1);
-  abpcon.zero();   
-  abpcon.put("CODCBL", codcbl);
-  if (abpcon.read() == NOERR)   
-    tmp = abpcon.get("DESCRIZ");
-  else
-    tmp = "";
-  return tmp;
+  return abpcon.get("DESCRIZ");
 }     
 
 bool CG1100_application::user_create()
 {
+	open_files(LF_NDITTE, LF_PCON, LF_TABCOM, LF_TAB, 0);
   _rel = new TRelation (LF_PCON);
-  _tab = new TTable(TAB_IVD);
   _msk = new TMask ("cg1100a") ;
   
-  _pcon = new TLocalisamfile (LF_PCON);
-
   TCursor *cursor = new TCursor (_rel);
 
   _cur_c1 = add_cursor (cursor);
-
   _rec = new TRectype (cursor->curr());  
-
-  _pcont_reclen = _rec->len();
-  _sort = new TSort(_pcont_reclen);
-
   _cur_c2 = add_cursor (NULL);
-
   add_file(LF_PCON);             
-
   _tipo_stampa = completa;
-  _salto_pag   = FALSE;
+  _salto_pag   = false;
   _bil  = new bil_ivd;
   _sort = new TSort();
-  return TRUE;
+
+  return true;
 }
 
 bool CG1100_application::user_destroy()
 {
   delete _rel;   
-  delete _tab;                         
-  delete _pcon;
-  //delete _tpcon;
   delete _msk;
   delete _rec;                      
-  //  delete _descr;
   delete _bil;
   delete _sort;
-  return TRUE;
+  return true;
 }
 
 int cg1100(int argc, char* argv[])
diff --git a/cg/cg3200.cpp b/cg/cg3200.cpp
index 35924108c..7e9d5e1b0 100755
--- a/cg/cg3200.cpp
+++ b/cg/cg3200.cpp
@@ -87,7 +87,7 @@ class TMastrini_application : public TPrintapp
   
   TDate _data_ini,_data_fine,_data_finese,_data_finesesucc,_ultima_data_reg;
   TDate _datareg,_datadoc,_data_inizioese,_datareg_stampa,_inizioes;
-  int _cur1,_cur2,_gruppo,_conto,_numcarat,_stampanum,_numivd,_annoiva;
+  int _cur1,_cur2,_gruppo,_conto,_numcarat,_stampanum,_annoiva;
   int _numrig,_natdoc,_tipo,_selez_mastrini,_g_prec,_c_prec,_numrivd_int;
   real _progredare,_progreavere,_totprogre_dare_al,_totprogre_avere_al;
   real _totprogre_dare,_totprogre_avere,_importo;
@@ -97,7 +97,7 @@ class TMastrini_application : public TPrintapp
   real _saldo_movimenti,_saldo_progressivi,_totale_saldo,_riporto_footer_dare,_riporto_footer_avere;
   TString _ragsoc,_indulc,_civulc,_capulc,_com,_prov,_comulc;
   long _codice_ditta,_s_prec;
-  TString _tipodoc,_codcaus,_descrcaus,_descrdociva,_regiva,_g_contr,_c_contr,_s_contr,_descrcontr;
+  TString _tipodoc,_codcaus,_descrcaus,_descrdociva,_regiva,_g_contr,_c_contr,_s_contr,_descrcontr,_numivd;
   char    _sezivd,_lettivd; 
   TString _descrizione,_sezione,_numdoc,_descrizionemov,_numrivd,_descr;
   TString _dataregs, _datadocs;
@@ -187,7 +187,7 @@ public:
   const char* descrizione_gruppo();
   const char* descrizione_conto();    
   const char* descrizione_sottoconto();
-  const char* descrizione_classe(char,char,int,int);
+  const char* descrizione_classe(char,char,int,const char *);
   bool almeno_un_record();
   void ricerca_dati_ditta();
   void conto(int,int,bool);                       
@@ -3385,20 +3385,20 @@ void TMastrini_application::ricerca_clifo()
   _lettivd = pconti.get_char(PCN_LETTIVD);
   numrivd  = pconti.get_int(PCN_NUMRIVD); 
   _numrivd = itor(numrivd);
-  _numivd  = pconti.get_int(PCN_NUMIVD);
+  _numivd  = pconti.get(PCN_NUMIVD);
 
-  descriz = descrizione_classe(_sezivd,_lettivd,numrivd,_numivd);    
+  descriz = descrizione_classe(_sezivd,_lettivd,numrivd, _numivd);    
  
-  if (_numivd != 0)      //Ora devo stampare la descrizione del livello della
-  {                      //classe immediatamente precedente a quello appena
-   if (_numrivd != "")   //stampato
-     descriz2 = descrizione_classe(_sezivd,_lettivd,_numrivd_int,0);
+  if (_numivd.not_empty())     //Ora devo stampare la descrizione del livello della
+  {                            //classe immediatamente precedente a quello appena
+   if (_numrivd.not_empty())   //stampato
+     descriz2 = descrizione_classe(_sezivd,_lettivd,_numrivd_int,"");
    else
-     descriz2 = descrizione_classe(_sezivd,_lettivd,0,0);
+     descriz2 = descrizione_classe(_sezivd,_lettivd,0,"");
   }
   else
-    if (_numrivd != "")
-      descriz2 = descrizione_classe(_sezivd,_lettivd,0,0);   
+    if (_numrivd.not_empty())
+      descriz2 = descrizione_classe(_sezivd,_lettivd,0,"");   
     else
       descriz2 = "";
  
@@ -3410,8 +3410,8 @@ void TMastrini_application::ricerca_clifo()
   else
     set_header (4, "%s@8g%c", TR("Classe") , _lettivd);  
   set_header (4, "@10g%-8s", (const char*) _numrivd);
-  if (_numivd != 0)
-    set_header (4, "@19g%2d", _numivd);
+  if (_numivd.not_empty())
+    set_header (4, "@19g%-4s", (const char *) _numivd);
   if (descriz2 != "")                              
   {
     set_header (4,"@23g%-50s",(const char*) descriz2);
@@ -3515,20 +3515,20 @@ int TMastrini_application::ricerca_clifo(int start)
   _lettivd = pconti.get_char(PCN_LETTIVD);
   numrivd  = pconti.get_int(PCN_NUMRIVD); 
   _numrivd = itor(numrivd);
-  _numivd  = pconti.get_int(PCN_NUMIVD);
-
+  _numivd  = pconti.get(PCN_NUMIVD);
+	
   descriz = descrizione_classe(_sezivd,_lettivd,numrivd,_numivd);    
  
-  if (_numivd != 0)      //Ora devo stampare la descrizione del livello della
+  if (_numivd.not_empty())      //Ora devo stampare la descrizione del livello della
   {                      //classe immediatamente precedente a quello appena
-   if (_numrivd != "")   //stampato
-     descriz2 = descrizione_classe(_sezivd,_lettivd,_numrivd_int,0);
+   if (_numrivd.not_empty())   //stampato
+     descriz2 = descrizione_classe(_sezivd,_lettivd,_numrivd_int,"");
    else
-     descriz2 = descrizione_classe(_sezivd,_lettivd,0,0);
+     descriz2 = descrizione_classe(_sezivd,_lettivd,0,"");
   }
   else
-    if (_numrivd != "")
-      descriz2 = descrizione_classe(_sezivd,_lettivd,0,0);   
+    if (_numrivd.not_empty())
+      descriz2 = descrizione_classe(_sezivd,_lettivd,0,"");   
     else
       descriz2 = "";
  
@@ -3540,9 +3540,9 @@ int TMastrini_application::ricerca_clifo(int start)
   else
     set_row(r, "%s@8g%c", TR("Classe"), _lettivd);
   set_row(r, "@10g%-8s", (const char*) _numrivd);
-  if (_numivd != 0)
-    set_row(r, "@19g%2d", _numivd);
-  if (descriz2 != "")                              
+  if (_numivd.not_empty())
+    set_row(r, "@19g%-4s", (const char *) _numivd);
+  if (descriz2.not_empty())                              
   {
     set_row(r,"@23g%-50s",(const char*) descriz2);
     set_row(r++,"@80g%-50s",(const char*) descriz);                                                  
@@ -3614,7 +3614,7 @@ void TMastrini_application::ricerca_classe_IV(bool scelta)
   _lettivd = pconti.get_char(PCN_LETTIVD);
   _numrivd_int  = pconti.get_int (PCN_NUMRIVD); 
   _numrivd = itor(_numrivd_int);
-  _numivd  = pconti.get_int (PCN_NUMIVD);
+  _numivd  = pconti.get(PCN_NUMIVD);
 }
  
 void TMastrini_application::ricerca_gruppo()
@@ -3628,16 +3628,16 @@ void TMastrini_application::ricerca_gruppo()
     ricerca_classe_IV (FALSE);  //Allora la cerco a livello di conto
                              
   descriz = descrizione_classe(_sezivd,_lettivd,_numrivd_int,_numivd);
-  if (_numivd != 0)      //Ora devo stampare la descrizione del livello della
+  if (_numivd.not_empty())      //Ora devo stampare la descrizione del livello della
   {                      //classe immediatamente precedente a quello appena
-   if (_numrivd != "")   //stampato
-     descriz2 = descrizione_classe(_sezivd,_lettivd,_numrivd_int,0);
+   if (_numrivd.not_empty())   //stampato
+     descriz2 = descrizione_classe(_sezivd,_lettivd,_numrivd_int,"");
    else
-     descriz2 = descrizione_classe(_sezivd,_lettivd,0,0);
+     descriz2 = descrizione_classe(_sezivd,_lettivd,0,"");
   }
   else
-    if (_numrivd != "")
-      descriz2 = descrizione_classe(_sezivd,_lettivd,0,0);   
+    if (_numrivd.not_empty())
+      descriz2 = descrizione_classe(_sezivd,_lettivd,0,"");   
     else
       descriz2 = "";
 
@@ -3650,9 +3650,9 @@ void TMastrini_application::ricerca_gruppo()
   else
     set_header (4, "@0g%s@12g%c", TR("Classe"), _lettivd);
   set_header (4, "@14g%-8s",(const char*) _numrivd); 
-  if (_numivd != 0)
-    set_header (4, "@23g%d", _numivd); 
-  if (descriz2 != "")
+  if (_numivd.not_empty())
+    set_header (4, "@23g%-4s", (const char *) _numivd); 
+  if (descriz2.not_empty())
   {
     set_header (4,"@27g%-50s",(const char*) descriz2);
     set_header (4,"@80g%-50s",(const char*) descriz);                                                  
@@ -3703,16 +3703,16 @@ int TMastrini_application::ricerca_gruppo(int start)
     ricerca_classe_IV (FALSE);  //Allora la cerco a livello di conto
                              
   descriz = descrizione_classe(_sezivd,_lettivd,_numrivd_int,_numivd);
-  if (_numivd != 0)      //Ora devo stampare la descrizione del livello della
+  if (_numivd.not_empty())      //Ora devo stampare la descrizione del livello della
   {                      //classe immediatamente precedente a quello appena
-   if (_numrivd != "")   //stampato
-     descriz2 = descrizione_classe(_sezivd,_lettivd,_numrivd_int,0);
+   if (_numrivd.not_empty())   //stampato
+     descriz2 = descrizione_classe(_sezivd,_lettivd,_numrivd_int,"");
    else
-     descriz2 = descrizione_classe(_sezivd,_lettivd,0,0);
+     descriz2 = descrizione_classe(_sezivd,_lettivd,0,"");
   }
   else
-    if (_numrivd != "")
-      descriz2 = descrizione_classe(_sezivd,_lettivd,0,0);   
+    if (_numrivd.not_empty())
+      descriz2 = descrizione_classe(_sezivd,_lettivd,0,"");   
     else
       descriz2 = "";
 
@@ -3725,8 +3725,8 @@ int TMastrini_application::ricerca_gruppo(int start)
   else
     set_row(r, "@0g%s@12g%c", TR("Classe"), _lettivd);
   set_row(r, "@14g%-8s",(const char*) _numrivd); 
-  if (_numivd != 0)
-    set_row(r, "@23g%d", _numivd); 
+  if (_numivd.not_empty())
+    set_row(r, "@23g%-4s", (const char *) _numivd); 
   if (descriz2 != "")
   {
     set_row(r,"@27g%-50s",(const char*) descriz2);
@@ -3781,7 +3781,7 @@ int TMastrini_application::ricerca_gruppo(int start)
   return r;
 }
 
-const char* TMastrini_application::descrizione_classe(char sezione, char lettera, int numr, int numero)
+const char* TMastrini_application::descrizione_classe(char sezione, char lettera, int numr, const char * numero)
 {
   TString16 key;
 
@@ -3793,9 +3793,9 @@ const char* TMastrini_application::descrizione_classe(char sezione, char lettera
     else                                         
     {
       if (numr != 0)
-        key.format("%c%c%04d%02d",sezione, lettera, numr,numero);
+        key.format("%c%c%04d%-4s",sezione, lettera, numr,numero);
       else
-        key.format("%c%c    %02d",sezione,lettera,numero);
+        key.format("%c%c    %-4s",sezione,lettera,numero);
     }
        
   return cache().get("%IVD", key, "S0");
diff --git a/cg/cg3400.cpp b/cg/cg3400.cpp
index db72e1ddf..d32069e80 100755
--- a/cg/cg3400.cpp
+++ b/cg/cg3400.cpp
@@ -1816,9 +1816,9 @@ bool TStampa_giornale::set_print(int)
     if (_stampa_definitiva) 
     {
       TEsercizi_contabili esc;
-      _ae_solare = _data_a.year();
       _ae = esc.date2esc(_data_a);
       _data_da = esc[_ae].inizio();
+      _ae_solare = _data_da.year(); // qui modificato
 
       // Controlla che non siano rimasti movimenti ancora da stampare dell'es.prec.
       if (_stampa_stesso_registro) 
diff --git a/cg/cg5800a.frm b/cg/cg5800a.frm
index 6d3639090..1dfe95eee 100755
--- a/cg/cg5800a.frm
+++ b/cg/cg5800a.frm
@@ -183,447 +183,347 @@ END
 
 STRINGA -1
 BEGIN
- PROMPT 1 23 " Non assegnati Op.Imponibili "
+  PROMPT 33 23 "@bOp. Imponibili"
+END
+
+STRINGA -1
+BEGIN
+  PROMPT 73 23 "Imposte"
+END
+
+STRINGA -1
+BEGIN
+ PROMPT 1 25 "Non assegnati"
 END
 
 VALUTA FFR_REGIMP(00) 18
-BEGIN
- PROMPT 29 23 ""
-END
-
-STRINGA -1
-BEGIN
- PROMPT 54 23 "Imposte"
-END
-
-VALUTA FFR_REGIVA(00) 18
-BEGIN
- PROMPT 62 23 ""
-END
-
-STRINGA -1
-BEGIN
- PROMPT 1 24 "   VT2 Abruzzo Op.Imponibili "
-END
-
-VALUTA FFR_REGIMP(01) 18
-BEGIN
- PROMPT 29 24 ""
-END
-
-STRINGA -1
-BEGIN
- PROMPT 54 24 "Imposte"
-END
-
-VALUTA FFR_REGIVA(01) 18
-BEGIN
- PROMPT 51 24 ""
-END
-
-STRINGA -1
-BEGIN
- PROMPT 1 25 "VT3 Basilicata Op.Imponibili "
-END
-
-VALUTA FFR_REGIMP(02) 18
 BEGIN
  PROMPT 29 25 ""
 END
 
-STRINGA -1
-BEGIN
- PROMPT 54 25 "Imposte"
-END
-
-VALUTA FFR_REGIVA(02) 18
+VALUTA FFR_REGIVA(00) 18
 BEGIN
  PROMPT 62 25 ""
 END
 
 STRINGA -1
 BEGIN
- PROMPT 1 26 "   VT4 Bolzano Op.Imponibili "
+ PROMPT 1 26 "VT2 Abruzzo"
 END
 
-VALUTA FFR_REGIMP(03) 18
+VALUTA FFR_REGIMP(01) 18
 BEGIN
  PROMPT 29 26 ""
 END
 
-STRINGA -1
+VALUTA FFR_REGIVA(01) 18
 BEGIN
- PROMPT 54 26 "Imposte"
-END
-
-VALUTA FFR_REGIVA(03) 18
-BEGIN
- PROMPT 62 26 ""
+ PROMPT 51 26 ""
 END
 
 STRINGA -1
 BEGIN
- PROMPT 1 27 "  VT5 Calabria Op.Imponibili "
+ PROMPT 1 27 "VT3 Basilicata"
 END
 
-VALUTA FFR_REGIMP(04) 18
+VALUTA FFR_REGIMP(02) 18
 BEGIN
  PROMPT 29 27 ""
 END
 
-STRINGA -1
-BEGIN
- PROMPT 54 27 "Imposte"
-END
-
-VALUTA FFR_REGIVA(04) 18
+VALUTA FFR_REGIVA(02) 18
 BEGIN
  PROMPT 62 27 ""
 END
 
 STRINGA -1
 BEGIN
- PROMPT 1 28 "  VT6 Campania Op.Imponibili "
+ PROMPT 1 28 "VT4 Bolzano"
 END
 
-VALUTA FFR_REGIMP(05) 18
+VALUTA FFR_REGIMP(03) 18
 BEGIN
  PROMPT 29 28 ""
 END
 
-STRINGA -1
-BEGIN
- PROMPT 54 28 "Imposte"
-END
-
-VALUTA FFR_REGIVA(05) 18
+VALUTA FFR_REGIVA(03) 18
 BEGIN
  PROMPT 62 28 ""
 END
 
 STRINGA -1
 BEGIN
- PROMPT 1 29 "VT7 Emilia Rom.Op.Imponibili "
+ PROMPT 1 29 "VT5 Calabria"
 END
 
-VALUTA FFR_REGIMP(06) 18
+VALUTA FFR_REGIMP(04) 18
 BEGIN
  PROMPT 29 29 ""
 END
 
-STRINGA -1
-BEGIN
- PROMPT 54 29 "Imposte"
-END
-
-VALUTA FFR_REGIVA(06) 18
+VALUTA FFR_REGIVA(04) 18
 BEGIN
  PROMPT 62 29 ""
 END
 
 STRINGA -1
 BEGIN
- PROMPT 1 30 "    VT8 Friuli Op.Imponibili "
+ PROMPT 1 30 "VT6 Campania"
 END
 
-VALUTA FFR_REGIMP(07) 18
+VALUTA FFR_REGIMP(05) 18
 BEGIN
  PROMPT 29 30 ""
 END
 
-STRINGA -1
-BEGIN
- PROMPT 54 30 "Imposte"
-END
-
-VALUTA FFR_REGIVA(07) 18
+VALUTA FFR_REGIVA(05) 18
 BEGIN
  PROMPT 62 30 ""
 END
 
 STRINGA -1
 BEGIN
- PROMPT 1 31 "     VT9 Lazio Op.Imponibili "
+ PROMPT 1 31 "VT7 Emilia Rom."
 END
 
-VALUTA FFR_REGIMP(08) 18
+VALUTA FFR_REGIMP(06) 18
 BEGIN
  PROMPT 29 31 ""
 END
 
-STRINGA -1
-BEGIN
- PROMPT 54 31 "Imposte"
-END
-
-VALUTA FFR_REGIVA(08) 18
+VALUTA FFR_REGIVA(06) 18
 BEGIN
  PROMPT 62 31 ""
 END
 
 STRINGA -1
 BEGIN
- PROMPT 1 32 "  VT10 Liguria Op.Imponibili "
+ PROMPT 1 32 "VT8 Friuli"
 END
 
-VALUTA FFR_REGIMP(09) 18
+VALUTA FFR_REGIMP(07) 18
 BEGIN
  PROMPT 29 32 ""
 END
 
-STRINGA -1
-BEGIN
- PROMPT 54 32 "Imposte"
-END
-
-VALUTA FFR_REGIVA(09) 18
+VALUTA FFR_REGIVA(07) 18
 BEGIN
  PROMPT 62 32 ""
 END
 
 STRINGA -1
 BEGIN
- PROMPT 1 33 "VT11 Lombardia Op.Imponibili "
+ PROMPT 1 33 "VT9 Lazio"
 END
 
-VALUTA FFR_REGIMP(10) 18
+VALUTA FFR_REGIMP(08) 18
 BEGIN
  PROMPT 29 33 ""
 END
 
-STRINGA -1
-BEGIN
- PROMPT 54 33 "Imposte"
-END
-
-VALUTA FFR_REGIVA(10) 18
+VALUTA FFR_REGIVA(08) 18
 BEGIN
  PROMPT 62 33 ""
 END
 
 STRINGA -1
 BEGIN
- PROMPT 1 34 "   VT12 Marche Op.Imponibili "
+ PROMPT 1 34 "VT10 Liguria"
 END
 
-VALUTA FFR_REGIMP(11) 18
+VALUTA FFR_REGIMP(09) 18
 BEGIN
- PROMPT 1 34 ""
+ PROMPT 29 34 ""
 END
 
-STRINGA -1
-BEGIN
- PROMPT 54 34 "Imposte"
-END
-
-VALUTA FFR_REGIVA(11) 18
+VALUTA FFR_REGIVA(09) 18
 BEGIN
  PROMPT 62 34 ""
 END
 
 STRINGA -1
 BEGIN
- PROMPT 1 35 "   VT13 Molise Op.Imponibili "
+ PROMPT 1 35 "VT11 Lombardia"
 END
 
-VALUTA FFR_REGIMP(12) 18
+VALUTA FFR_REGIMP(10) 18
 BEGIN
  PROMPT 29 35 ""
 END
 
-STRINGA -1
-BEGIN
- PROMPT 54 35 "Imposte"
-END
-
-VALUTA FFR_REGIVA(12) 18
+VALUTA FFR_REGIVA(10) 18
 BEGIN
  PROMPT 62 35 ""
 END
 
 STRINGA -1
 BEGIN
- PROMPT 1 36 " VT14 Piemonte Op.Imponibili "
+ PROMPT 1 36 "VT12 Marche"
 END
 
-VALUTA FFR_REGIMP(13) 18
+VALUTA FFR_REGIMP(11) 18
 BEGIN
  PROMPT 1 36 ""
 END
 
-STRINGA -1
-BEGIN
- PROMPT 54 36 "Imposte"
-END
-
-VALUTA FFR_REGIVA(13) 18
+VALUTA FFR_REGIVA(11) 18
 BEGIN
  PROMPT 62 36 ""
 END
 
 STRINGA -1
 BEGIN
- PROMPT 1 37 "   VT15 Puglia Op.Imponibili "
+ PROMPT 1 37 "VT13 Molise"
 END
 
-VALUTA FFR_REGIMP(14) 18
+VALUTA FFR_REGIMP(12) 18
 BEGIN
  PROMPT 29 37 ""
 END
 
-STRINGA -1
-BEGIN
- PROMPT 54 37 "Imposte"
-END
-
-VALUTA FFR_REGIVA(14) 18
+VALUTA FFR_REGIVA(12) 18
 BEGIN
  PROMPT 62 37 ""
 END
 
 STRINGA -1
 BEGIN
- PROMPT 1 38 " VT16 Sardegna Op.Imponibili "
+ PROMPT 1 38 "VT14 Piemonte"
 END
 
-VALUTA FFR_REGIMP(15) 18
+VALUTA FFR_REGIMP(13) 18
 BEGIN
- PROMPT 29 38 ""
+ PROMPT 1 38 ""
 END
 
-STRINGA -1
-BEGIN
- PROMPT 54 38 "Imposte"
-END
-
-VALUTA FFR_REGIVA(15) 18
+VALUTA FFR_REGIVA(13) 18
 BEGIN
  PROMPT 62 38 ""
 END
 
 STRINGA -1
 BEGIN
- PROMPT 1 39 "  VT17 Sicilia Op.Imponibili "
+ PROMPT 1 39 "VT15 Puglia"
 END
 
-VALUTA FFR_REGIMP(16) 18
+VALUTA FFR_REGIMP(14) 18
 BEGIN
  PROMPT 29 39 ""
 END
 
-STRINGA -1
-BEGIN
- PROMPT 54 39 "Imposte"
-END
-
-VALUTA FFR_REGIVA(16) 18
+VALUTA FFR_REGIVA(14) 18
 BEGIN
  PROMPT 62 39 ""
 END
 
 STRINGA -1
 BEGIN
- PROMPT 1 40 "  VT18 Toscana Op.Imponibili "
+ PROMPT 1 40 "VT16 Sardegna"
 END
 
-VALUTA FFR_REGIMP(17) 18
+VALUTA FFR_REGIMP(15) 18
 BEGIN
  PROMPT 29 40 ""
 END
 
-STRINGA -1
-BEGIN
- PROMPT 54 40 "Imposte"
-END
-
-VALUTA FFR_REGIVA(17) 18
+VALUTA FFR_REGIVA(15) 18
 BEGIN
  PROMPT 62 40 ""
 END
 
 STRINGA -1
 BEGIN
- PROMPT 1 41 "   VT19 Trento Op.Imponibili "
+ PROMPT 1 41 "VT17 Sicilia"
 END
 
-VALUTA FFR_REGIMP(18) 18
+VALUTA FFR_REGIMP(16) 18
 BEGIN
  PROMPT 29 41 ""
 END
 
-STRINGA -1
-BEGIN
- PROMPT 54 41 "Imposte"
-END
-
-VALUTA FFR_REGIVA(18) 18
+VALUTA FFR_REGIVA(16) 18
 BEGIN
  PROMPT 62 41 ""
 END
 
 STRINGA -1
 BEGIN
- PROMPT 1 42 "   VT20 Umbria Op.Imponibili "
+ PROMPT 1 42 "VT18 Toscana"
 END
 
-VALUTA FFR_REGIMP(19) 18
+VALUTA FFR_REGIMP(17) 18
 BEGIN
  PROMPT 29 42 ""
 END
 
-STRINGA -1
-BEGIN
- PROMPT 54 42 "Imposte"
-END
-
-VALUTA FFR_REGIVA(19) 18
+VALUTA FFR_REGIVA(17) 18
 BEGIN
  PROMPT 62 42 ""
 END
 
 STRINGA -1
 BEGIN
- PROMPT 1 43 "VT21 Valle d'Aosta op.impon. "
+ PROMPT 1 43 "VT19 Trento"
 END
 
-VALUTA FFR_REGIMP(20) 18
+VALUTA FFR_REGIMP(18) 18
 BEGIN
  PROMPT 29 43 ""
 END
 
-STRINGA -1
-BEGIN
- PROMPT 54 43 "Imposte"
-END
-
-VALUTA FFR_REGIVA(20) 18
+VALUTA FFR_REGIVA(18) 18
 BEGIN
  PROMPT 62 43 ""
 END
 
 STRINGA -1
 BEGIN
- PROMPT 1 44 "   VT22 Veneto Op.Imponibili "
+ PROMPT 1 44 "VT20 Umbria"
 END
 
-VALUTA FFR_REGIMP(21) 18
+VALUTA FFR_REGIMP(19) 18
 BEGIN
  PROMPT 29 44 ""
 END
 
-STRINGA -1
-BEGIN
- PROMPT 54 44 "Imposte"
-END
-
-VALUTA FFR_REGIVA(21) 18
+VALUTA FFR_REGIVA(19) 18
 BEGIN
  PROMPT 62 44 ""
 END
 
 STRINGA -1
 BEGIN
-  PROMPT 2 46 "______________________________________________________________________________"
+ PROMPT 1 45 "VT21 Valle d'Aosta"
+END
+
+VALUTA FFR_REGIMP(20) 18
+BEGIN
+ PROMPT 29 45 ""
+END
+
+VALUTA FFR_REGIVA(20) 18
+BEGIN
+ PROMPT 62 45 ""
+END
+
+STRINGA -1
+BEGIN
+ PROMPT 1 46 "VT22 Veneto"
+END
+
+VALUTA FFR_REGIMP(21) 18
+BEGIN
+ PROMPT 29 46 ""
+END
+
+VALUTA FFR_REGIVA(21) 18
+BEGIN
+ PROMPT 62 46 ""
+END
+
+STRINGA -1
+BEGIN
+  PROMPT 2 48 "______________________________________________________________________________"
 END
 
 END
diff --git a/cg/cg5800b.uml b/cg/cg5800b.uml
index ab08decbf..316b9a3fe 100755
--- a/cg/cg5800b.uml
+++ b/cg/cg5800b.uml
@@ -429,7 +429,7 @@ END
 
 CURRENCY FM_REGIMP(20) 18
 BEGIN
- PROMPT 1 18 "VT21 Valle d'Aosta op.impon. "
+ PROMPT 1 18 "VT21 Valle d'Aosta           "
  FLAGS "D"
 END
 
diff --git a/cg/cg5800ra.rep b/cg/cg5800ra.rep
index acd406f09..5fd2864cc 100755
--- a/cg/cg5800ra.rep
+++ b/cg/cg5800ra.rep
@@ -94,7 +94,8 @@
    <prescript description="F3.102 PRESCRIPT">MESSAGE ADD,F2.202</prescript>
   </field>
  </section>
- <sql>USE RMOVIVA  SE (23.TIPO=="C")&#26;&#26;(23.ANNOIVA=#ANNO)&#26;&#26;(20.ALLEG=="6")&#26;&#26;(202@.S1=="") BY 23.ANNOIVA 13.CODREG 23.TIPO 23.CODCF NUMREG
+ <sql>USE RMOVIVA  SE (23.TIPO=="C")&#26;&#26;(23.ANNOIVA=#ANNO)&#26;&#26;(20.ALLEG=="6")&#26;&#26;(202@.S1=="")
+BY 23.ANNOIVA 13.CODREG 23.TIPO 23.CODCF NUMREG
 JOIN MOV INTO NUMREG==NUMREG
 JOIN CLIFO TO MOV INTO TIPOCF==TIPO CODCF==CODCF
 JOIN COMUNI TO CLIFO INTO STATO==STATOCF COM==COMCF
diff --git a/cg/cg7200.cpp b/cg/cg7200.cpp
index f357ab47e..2d904f697 100755
--- a/cg/cg7200.cpp
+++ b/cg/cg7200.cpp
@@ -16,9 +16,13 @@
 #include <mov.h>
 #include <rmov.h>
 #include <rmoviva.h>
+#include <pagsca.h>
+#include <partite.h>
 
 #define ALIAS_PCON1		100
 #define ALIAS_PCON2		200
+#define ALIAS_ABPCON1	300
+#define ALIAS_ABPCON2	400
  
 class TInvioP_file: public TFile_text
 {
@@ -73,19 +77,25 @@ class TInvioP : public TSkeleton_application
 	TCursor*				   _cur;
   TInvioP_mask* 		 _msk;
   TInvioP_file*			 _trasfile;
+	TInvioP_file*			 _trasfilepag;
   TDate							 _dataini, _datafin;
+	long							 _nregcosto, _nregpag;
+	real							 _importo;
   
 protected:
   virtual bool create(void);
   virtual bool destroy(void);
   virtual void main_loop() ;
   void invio_proforma();
-  bool i_proforma_movimenti();
+  bool i_proforma_movimenti(const bool pagamenti);
   bool i_proforma_righe();
+  bool i_proforma_pagamenti(const TCursor& cur);
   bool i_proforma_clifor(char tipocf = 'C');
   bool i_proforma_conti();
-  bool i_proforma_pagamenti();
 public:
+	const real get_importo() {return _importo;};
+	const long get_nregcosto() {return _nregcosto;};
+	const long get_nregpag() {return _nregpag;};
   TInvioP() {};
   virtual ~TInvioP() {};
 };  
@@ -117,15 +127,46 @@ void TInvioP_file::validate(TCursor& cur,TRecord_text &rec, TToken_string &s, TS
 		valore << str;
 		valore.trim();
 	}
+	else if (code == "_CODCBL")
+	{
+		valore = str;
+		int i = valore.find("$");
+		valore = valore.left(i);
+	}
+	else if (code == "_RAGSOC")
+	{
+		valore = str;
+		valore = valore.strip_d_spaces();
+	}
+	else if (code == "_FLAG")
+	{
+		const char chiusa = str[0];
+		valore = (chiusa=='X') ? "S" : "A";
+
+	}
+	else if (code == "_NREGCOSTO")
+	{
+		valore = app().get_nregcosto();
+	}
+	else if (code == "_NREGPAG")
+	{
+		valore = app().get_nregpag();
+	}
+	else if (code == "_IMPORTO")
+	{
+		valore = app().get_importo().string();
+	}
+
   else NFCHECK("Macro non definita: %s", (const char *)code);
   str = valore;
 }
 
 bool TInvioP::create()
 {               
-	open_files(LF_CAUSALI, LF_CLIFO, LF_PCON, LF_MOV, LF_RMOV, LF_RMOVIVA, 0);
+	open_files(LF_CAUSALI, LF_CLIFO, LF_PCON, LF_MOV, LF_RMOV, LF_RMOVIVA, LF_ABPCON, LF_PARTITE, 0);
   _msk = new TInvioP_mask();
   _trasfile = NULL;
+  _trasfilepag = NULL;
   return TSkeleton_application::create();
 }
 
@@ -133,6 +174,8 @@ bool TInvioP::destroy()
 {             
 	if (_trasfile)  
   	delete _trasfile;
+	if (_trasfilepag)  
+  	delete _trasfilepag;
   delete _msk;
 
   return TSkeleton_application::destroy();
@@ -161,7 +204,7 @@ void TInvioP::invio_proforma()
 {
 	if (_msk->get_bool(F_MOVIMENTI))
 	{
-		i_proforma_movimenti();
+		i_proforma_movimenti(_msk->get_bool(F_PAGAMENTI));
 		i_proforma_righe();
   }
 	if (_msk->get_bool(F_CLIENTI))
@@ -177,7 +220,7 @@ bool TInvioP::i_proforma_conti()
 	TFilename configname = "proforma.ini";
 	TConfig configfile(configname);
 	TFilename filename = _msk->get(F_DESTINAZIONE);
-	filename.add("PIANOCON.TXT");
+	filename.add("pianocon.txt");
 	if (fexist(filename))
 		remove(filename);	
 	_trasfile = new TInvioP_file(filename, configname);
@@ -204,17 +247,27 @@ bool TInvioP::i_proforma_conti()
   return TRUE;
 }
 
-bool TInvioP::i_proforma_movimenti()
+bool TInvioP::i_proforma_movimenti(const bool pagamenti)
 {
 	TFilename configname = "proforma.ini";
 	TConfig configfile(configname);
 	TFilename filename = _msk->get(F_DESTINAZIONE);
-	filename.add("REGISTRA.TXT");
+	filename.add("registra.txt");
 	if (fexist(filename))
 		remove(filename);	
 	_trasfile = new TInvioP_file(filename, configname);
 	_trasfile->open(filename,'w');
 	_trasfile->force_record_separator();
+	if (pagamenti)
+	{
+		TFilename filenamepag = _msk->get(F_DESTINAZIONE);
+		filenamepag.add("pagament.txt");
+		if (fexist(filenamepag))
+			remove(filenamepag);	
+		_trasfilepag = new TInvioP_file(filenamepag, configname);
+		_trasfilepag->open(filenamepag,'w');
+		_trasfilepag->force_record_separator();
+	}
 	TRectype da(LF_MOV);
   TRectype a(LF_MOV);
   da.put(MOV_DATAREG, _dataini);
@@ -234,11 +287,19 @@ bool TInvioP::i_proforma_movimenti()
 			rec.set_type("T");
 			_trasfile->autoload(rec, cur); 
 			_trasfile->write(rec);
+			if (pagamenti)
+				i_proforma_pagamenti(cur);
     }	
   } 
 	_trasfile->close();
 	delete _trasfile;
 	_trasfile = NULL;
+	if (pagamenti)
+	{
+		_trasfilepag->close();
+		delete _trasfilepag;
+		_trasfilepag = NULL;
+	}
 	return TRUE;                 
 }
 
@@ -247,7 +308,7 @@ bool TInvioP::i_proforma_righe()
 	TFilename configname = "proforma.ini";
 	TConfig configfile(configname);
 	TFilename filename = _msk->get(F_DESTINAZIONE);
-	filename.add("RIGHE.TXT");
+	filename.add("righe.txt");
 	if (fexist(filename))
 		remove(filename);	
 	_trasfile = new TInvioP_file(filename, configname);
@@ -262,14 +323,9 @@ bool TInvioP::i_proforma_righe()
   rel.add(LF_RMOV, "NUMREG==NUMREG", 1);
   rel.add(LF_PCON, "GRUPPO==GRUPPO|CONTO==CONTO|SOTTOCONTO==SOTTOCONTO", 1, LF_RMOV, ALIAS_PCON1);
   rel.add(LF_PCON, "GRUPPO==GRUPPO|CONTO==CONTO|SOTTOCONTO==SOTTOCONTO", 1, LF_RMOVIVA, ALIAS_PCON2);
-
-  bool add(int logicnum, const char* relexprs, int key = 1, int linkto = 0, int alias = 0, bool allow_lock = FALSE);
-
-  //rel.add("REG", "CODTAB[1,4]==ANNOIVA|CODTAB[5,7]==REG", 1);
-  //TString filtro = "(23->PROTIVA != \"\") && ";
- 	//filtro << "(REG->I0 == 1) || (REG->I0 == 2)";
+  rel.add(LF_ABPCON, "CODCBL==CODCBL", 1, -ALIAS_PCON1, ALIAS_ABPCON1);
+  rel.add(LF_ABPCON, "CODCBL==CODCBL", 1, -ALIAS_PCON2, ALIAS_ABPCON2);
   TCursor cur(&rel, "", 2, &da, &a);
-  //cur.setfilter(filtro, TRUE);
   const long cur_items = cur.items();
   if (cur_items != 0) 
   {               
@@ -314,15 +370,88 @@ bool TInvioP::i_proforma_righe()
 	return TRUE;
 }
 
+bool TInvioP::i_proforma_pagamenti(const TCursor& cur)
+{
+	const char tipomov = cur.curr().get(MOV_TIPOMOV)[0];
+	if (tipomov == '3' || tipomov == '2' || tipomov == '6')
+	{
+		TRelation relpart(LF_PARTITE);
+		TRectype da(LF_PARTITE);
+		da.put(PART_NREG, cur.curr().get(MOV_NUMREG));
+		TCursor curpart(&relpart,	"", 2, &da, &da);
+	  const long curpart_items = curpart.items();
+		if (curpart_items != 0) 
+		{               
+			curpart.freeze();
+			TRectype& curpart_rec = curpart.curr();
+			for (curpart = 0; curpart.pos() < curpart_items; ++(curpart))
+			{
+				TRelation relpag(LF_PAGSCA);
+				TRectype da(LF_PAGSCA);
+				da.put(PAGSCA_TIPOC, curpart_rec.get(PART_TIPOCF));
+				da.put(PAGSCA_GRUPPO, curpart_rec.get(PART_GRUPPO));
+				da.put(PAGSCA_CONTO, curpart_rec.get(PART_CONTO));
+				da.put(PAGSCA_SOTTOCONTO, curpart_rec.get(PART_SOTTOCONTO));
+				da.put(PAGSCA_ANNO, curpart_rec.get(PART_ANNO));
+				da.put(PAGSCA_NUMPART, curpart_rec.get(PART_NUMPART));
+				const int nrigapart = curpart_rec.get_int(PART_NRIGA);
+				TString80 filtro;
+				filtro.format("NRIGP == %d", nrigapart);
+				TCursor curpag(&relpart, filtro, 1, &da, &da);
+				const long curpag_items = curpag.items();
+				if (curpag_items != 0) 
+				{  
+					TAssoc_array pagame;
+					pagame.destroy();
+					curpag.freeze();
+					TRectype& curpag_rec = curpag.curr();
+					for (curpag = 0; curpag.pos() < curpag_items; ++(curpag))
+					{
+						TString80 indice = curpag_rec.get(PAGSCA_ANNO);
+						indice << '|' << curpag_rec.get(PAGSCA_NUMPART);
+						indice << '|' << curpag_rec.get(PAGSCA_NRIGA);
+						real importo = ZERO;
+				    bool is_key = pagame.is_key(indice);
+						real& somma = is_key ? (real&) pagame[indice] : importo;
+						somma += curpag_rec.get_real(PAGSCA_IMPORTO);
+					  if (!is_key)
+							pagame.add(indice, somma);
+					}
+					// scrivo i record risultanti
+					real* cp;
+				  for (cp = (real*) pagame.first_item(); cp != NULL; cp = (real*) pagame.succ_item())
+					{
+						TToken_string keypart;
+						keypart << curpart_rec.get(PART_TIPOCF);
+						keypart << curpart_rec.get(PART_GRUPPO);
+						keypart << curpart_rec.get(PART_CONTO);
+						keypart << curpart_rec.get(PART_SOTTOCONTO);
+						keypart << pagame.get_hashobj()->key();
+						const TRectype& partita = cache().get(LF_PARTITE, keypart);
+						_nregpag = cur.curr().get_long(MOV_NUMREG);
+						_nregcosto = partita.get_long(PART_NREG);
+						_importo = *cp;
+						TRecord_text recpag;
+						recpag.set_type("G");
+						_trasfilepag->autoload(recpag, curpag); 
+						_trasfilepag->write(recpag);
+					}
+				}
+			}
+		}
+	}
+	return TRUE;
+}
+
 bool TInvioP::i_proforma_clifor(char tipocf)
 {
 	TFilename configname = "proforma.ini";
 	TConfig configfile(configname);
 	TFilename filename = _msk->get(F_DESTINAZIONE);
 	if (tipocf == 'C')
-		filename.add("CLIENTI.TXT");
+		filename.add("clienti.txt");
 	else
-		filename.add("FORNIT.TXT");
+		filename.add("fornit.txt");
 	if (fexist(filename))
 		remove(filename);	
 	_trasfile = new TInvioP_file(filename, configname);
diff --git a/cg/cgp4.cpp b/cg/cgp4.cpp
index 202eb4129..79af609d5 100755
--- a/cg/cgp4.cpp
+++ b/cg/cgp4.cpp
@@ -10,6 +10,8 @@ int main(int argc,char** argv)
   {
   case 0 :
   default: cgp4100(argc,argv) ; break;  // Importa stipendi in prima nota (OMASA)
+  case 1 :
+  default: cgp4200(argc,argv) ; break;  // Importazione clienti (GSA/CODFIDI)
   }                                  
   exit(0);
   return 0;
diff --git a/cg/f19.dir b/cg/f19.dir
index aa182a45b..d905daca6 100755
--- a/cg/f19.dir
+++ b/cg/f19.dir
@@ -1,3 +1,3 @@
 19
 0
-$pcon|798|798|144|7|Piano dei conti|NCON||
+$pcon|||147|0|Piano dei conti|NCON||
diff --git a/cg/f19.trr b/cg/f19.trr
index fdca7773b..5f9830655 100755
--- a/cg/f19.trr
+++ b/cg/f19.trr
@@ -16,11 +16,11 @@ SOSPESO|8|1|0|Conto sospeso
 SEZIVD|1|1|0|Sezione IV direttiva CEE
 LETTIVD|1|1|0|Lettera IV direttiva CEE
 NUMRIVD|1|8|0|Numero romano IV direttiva CEE
-NUMIVD|2|2|0|Numero IV Direttiva CEE
+NUMIVD|1|4|0|Numero IV Direttiva CEE
 SEZIVDOPP|1|1|0|Sezione di sezione opposta IV direttiva CEE
 LETTIVDOPP|1|1|0|Lettera di sezione opposta IV direttiva CEE
 NUMRIVDOPP|1|8|0|Numero romano di sezione opposta IV direttiva CEE
-NUMIVDOPP|2|2|0|Numero di sezione opposta IV direttiva CEE
+NUMIVDOPP|1|4|0|Numero di sezione opposta IV direttiva CEE
 RICSER|2|1|0|Ricavi per servizi
 IVACOMP|1|4|0|Codice IVA di compensazione per regimi agricoli
 CMSNEEDED|8|1|0|Codice cdc/commessa obbligatorio in prima nota
diff --git a/cg/proforma.ini b/cg/proforma.ini
index 8f2635a6a..546cb2e42 100755
--- a/cg/proforma.ini
+++ b/cg/proforma.ini
@@ -222,7 +222,8 @@ NAME(14) = VOCE DI SPESA
 TYPE(14) = STRINGA
 POSITION(14) = 145
 LENGTH(14) = 10
-FIELD(14) = 100@->CODCBL
+MESSAGE(14) = _CODCBL
+FIELD(14) = 300@->DESCRIZ
 
 [RECORD I]
 
@@ -303,7 +304,8 @@ NAME(14) = VOCE DI SPESA
 TYPE(14) = STRINGA
 POSITION(14) = 145
 LENGTH(14) = 10
-FIELD(14) = 200@->CODCBL
+MESSAGE(14) = _CODCBL
+FIELD(14) = 400@->DESCRIZ
 
 [RECORD C]
 
@@ -317,7 +319,8 @@ NAME(1) = RAGIONE SOCIALE
 TYPE(1) = STRINGA
 POSITION(1) = 11
 LENGTH(1) = 40
-FIELD(1) = 20->RAGSOC[1,40]
+MESSAGE(1) = _RAGSOC
+FIELD(1) = 20->RAGSOC
 
 NAME(2) = PARTITA IVA
 TYPE(2) = STRINGA
@@ -388,6 +391,36 @@ POSITION(3) = 15
 LENGTH(3) = 80
 FIELD(3)=19->DESCR
 
+[RECORD G]
+NAME(0) = ID REGISTRAZIONE PAGAMENTO
+TYPE(0) = NUMERO
+POSITION(0) = 0
+LENGTH(0) = 10
+MESSAGE(0) = _NREGPAG
+
+NAME(1) = ID REGISTRAZIONE COSTO
+TYPE(1) = NUMERO
+POSITION(1) = 10
+LENGTH(1) = 10
+MESSAGE(1) = _NREGCOSTO
+
+NAME(2) = IMPORTO
+TYPE(2) = IMPORTO
+POSITION(2) = 20
+MESSAGE(2) = _IMPORTOPAG
+
+NAME(3) = FLAG ACCONTO/SALDO
+TYPE(3) = STRINGA
+POSITION(3) = 34
+LENGTH(3) = 1
+MESSAGE(3) = _FLAG
+
+NAME(4) = VALUTA
+TYPE(4) = STRINGA
+POSITION(4) = 35
+LENGTH(4) = 1
+MESSAGE(4)=_FISSO,!1
+
 [OPZIONI]
 PERCORSO = C:\TEMP\
 
diff --git a/cm/cm0100.cpp b/cm/cm0100.cpp
index 5ac83203a..67afc3ef1 100755
--- a/cm/cm0100.cpp
+++ b/cm/cm0100.cpp
@@ -10,6 +10,7 @@
 #include "cm0100a.h"
 #include "cm0100.h"
 
+#include "mov.h"
 #include "rmov.h"
 #include "pconti.h"
 
@@ -19,9 +20,12 @@
 
 class TForm_contixcdc : public TForm
 { 
+  static TForm_contixcdc* _cur_form;
+  static void conti_header_handler(TPrinter& p);
+
 public:
   virtual bool validate(TForm_item &cf, TToken_string &s);
-  void set_testata() { set_header(1, false); set_header(1, true); }
+  void set_testata();
   void set_pedata() { set_footer(1, false); set_footer(1, true); }
   TPrint_section& get_section(char s, pagetype pos);
   
@@ -29,6 +33,34 @@ public:
   virtual ~TForm_contixcdc();
 };
 
+TForm_contixcdc* TForm_contixcdc::_cur_form = NULL;
+
+void TForm_contixcdc::conti_header_handler(TPrinter& p)
+{              
+  TForm_contixcdc& f = *_cur_form;
+  if (f.firstpage_is_lastpage()) 
+  {
+    f.set_background(1, TRUE);
+    f.set_header(1, TRUE);
+    f.set_footer(0, FALSE);
+  } 
+  else 
+  {
+    const word page = f.page(p);
+    f.set_background(page, TRUE);
+    f.set_header(1, TRUE);
+    f.set_footer(page, FALSE);
+  }
+}
+
+void TForm_contixcdc::set_testata() 
+{ 
+  set_header(1, false); set_header(1, true); 
+  _cur_form = this;
+  printer().setheaderhandler(conti_header_handler); // Setta handlers
+}
+
+
 TPrint_section& TForm_contixcdc::get_section(char s, pagetype pos) 
 { 
   if (!exist(s, pos))
@@ -135,6 +167,13 @@ bool TContixcdc_mask::on_field_event(TOperable_field& o, TField_event e, long jo
 					return error_box(TR("La data iniziale non pu� essere precedente alla data inizio esercizio %s"), (const char*) datainies.string());
 			}	  		
   	}
+    if (e == fe_close)
+    {
+      const int annoes = get_int(F_ANNO);
+      const TDate dataini = get(F_DATAINI);
+      if (annoes == 0 && !dataini.ok())
+        return error_box(TR("Data iniziale obbligatoria se anno esercizio non specificato"));
+    }
   	break;
   case F_DATAFIN:
   	if (e == fe_modify || fe_close)  
@@ -147,6 +186,13 @@ bool TContixcdc_mask::on_field_event(TOperable_field& o, TField_event e, long jo
 				  return error_box(FR("La data finale non pu� essere successiva alla data fine esercizio %s"), (const char*) datafines.string());
 			}	  		
   	}
+    if (e == fe_close)
+    {
+      const int annoes = get_int(F_ANNO);
+      const TDate datafin = get(F_DATAFIN);
+      if (annoes == 0 && !datafin.ok())
+        return error_box(TR("Data finale obbligatoria se anno esercizio non specificato"));
+    }
   	break;	
   default: break;
   }  
@@ -232,7 +278,7 @@ bool TContixCdc::destroy()
 
 void TContixCdc::print_sottoc()
 {                            
-	if (!_t_sottoc._tot_periodo.is_zero())
+	if (!_t_sottoc._tot_periodo.is_zero() || !_t_sottoc._tot_progprec.is_zero())
 	{
 		if (_headercms)
 		{
@@ -361,6 +407,7 @@ void TContixCdc::print_special_section(char type, pagetype pos)
 void TContixCdc::print_body(pagetype pos)
 {                                          
   print_special_section('B', pos);
+  _form->set_testata();
 }
 
 void TContixCdc::set_field(pagetype pos, int id, const real& val)
@@ -433,6 +480,9 @@ void TContixCdc::main_loop()
   	TString80 acdc 	= _mask->get(F_ACDC); 	// cdc/commessa finale
   	TString80 afsc 	= _mask->get(F_AFSC);   // fase finale
     TRelation relrmov(LF_RMOV);
+    if (_codes > 0)
+      relrmov.add(LF_MOV, "NUMREG==NUMREG");  //aggiunge le testate per avere la datacomp
+
 	  TString filtro = "";
 	  if (_codes > 0)
 	  	filtro.format("ANNOES==%d", _codes);
@@ -515,7 +565,7 @@ void TContixCdc::main_loop()
     	_currsottoc = rmovrec.get_long(RMV_SOTTOCONTO);
     	_currgruppo = rmovrec.get_int(RMV_GRUPPO);
     	_currconto = rmovrec.get_int(RMV_CONTO);
-   		TDate datareg = rmovrec.get_date(RMV_DATAREG);
+
    		const TImporto importo(rmovrec.get_char(RMV_SEZIONE), rmovrec.get_real(RMV_IMPORTO));
   		if ((_oldcms != _currcms) || (_oldfsc != _currfsc) || (_oldgruppo != _currgruppo) || (_oldconto != _currconto) || (_oldsottoc != _currsottoc))
     	{
@@ -532,8 +582,16 @@ void TContixCdc::main_loop()
 					}	
 				}	
 			}
-  		aggiorna_totali(importo, datareg);
-    } 
+
+      TDate data;
+      if (_codes > 0)
+        data = relrmov.curr(LF_MOV).get_date(MOV_DATACOMP);
+      else
+        data = rmovrec.get_date(RMV_DATAREG);
+
+  		aggiorna_totali(importo, data);
+    }   //fine for
+    
     if (num > 0)
     {
 	    print_sottoc();
diff --git a/cm/cm0100a.frm b/cm/cm0100a.frm
index 44dd83891..1cfc4590b 100755
--- a/cm/cm0100a.frm
+++ b/cm/cm0100a.frm
@@ -35,9 +35,9 @@ END
 
 NUMERO 4 7
 BEGIN
-	KEY "Nr. pagina"
-	PROMPT  120 1 "Pag. "
-	MESSAGE _PAGENO
+  KEY "Nr. pagina"
+  PROMPT  120 1 "Pag. "
+  MESSAGE _PAGENO
 END
 
 STRINGA -1 22
@@ -88,6 +88,12 @@ BEGIN
   PROMPT 40 6 "a fase: "
 END
 
+STRINGA -1
+BEGIN
+  KEY "Intestazione stampa"
+  PROMPT 1 7 "____________________________________________________________________________________________________________________________________"
+END
+
 END // section header first
 
 // intestazione comessa
diff --git a/cm/cm0200.cpp b/cm/cm0200.cpp
index 87a03649d..79c1c1f4c 100755
--- a/cm/cm0200.cpp
+++ b/cm/cm0200.cpp
@@ -17,12 +17,15 @@
 
 class TForm_schedacdc : public TForm
 { 
-   
+  static TForm_schedacdc* _cur_form;
+  static void conti_header_handler(TPrinter& p);
+
 public:
   virtual bool validate(TForm_item &cf, TToken_string &s);
-  void set_testata() {set_header(1,TRUE);}
+  void set_testata();
   TPrint_section& get_body() {return section('B', odd_page);}
   TPrint_section& get_section(char s, pagetype pos) {return section(s, pos);}
+
   TForm_schedacdc();
   virtual ~TForm_schedacdc();
 };
@@ -35,6 +38,35 @@ TForm_schedacdc::~TForm_schedacdc() //distruttore
 { 
 }
 
+//pazzesco (ma forse unico) modo di stampare i numeri pagina progressivi senza poter usare la
+//print() standard dei TForm; e' stata reimplementata la header_handler() come conti_header_handler()
+TForm_schedacdc* TForm_schedacdc::_cur_form = NULL;
+
+void TForm_schedacdc::conti_header_handler(TPrinter& p)
+{              
+  TForm_schedacdc& f = *_cur_form;
+  if (f.firstpage_is_lastpage()) 
+  {
+    f.set_background(1, TRUE);
+    f.set_header(1, TRUE);
+    f.set_footer(0, FALSE);
+  } 
+  else 
+  {
+    const word page = f.page(p);
+    f.set_background(page, TRUE);
+    f.set_header(1, TRUE);
+    f.set_footer(page, FALSE);
+  }
+}
+
+void TForm_schedacdc::set_testata() 
+{ 
+  set_header(1, false); set_header(1, true); 
+  _cur_form = this;
+  printer().setheaderhandler(conti_header_handler); // Setta handlers
+}
+
 bool TForm_schedacdc::validate(TForm_item &cf, TToken_string &s)
 {
   const TString code(s.get(0)); // prende il primo parametro, il codice del messaggio
@@ -119,6 +151,13 @@ bool TSchedacdc_mask::on_field_event(TOperable_field& o, TField_event e, long jo
 					return error_box(FR("La data iniziale non pu� essere precedente alla data inizio esercizio %s"), (const char*) datainies.string());
 			}	  		
   	}
+    if (e == fe_close)
+    {
+      const int annoes = get_int(F_ANNO);
+      const TDate dataini = get(F_DATAINI);
+      if (annoes == 0 && !dataini.ok())
+        return error_box(TR("Data iniziale obbligatoria se anno esercizio non specificato"));
+    }
   	break;
   case F_DATAFIN:
   	if (e == fe_modify || fe_close)  
@@ -134,6 +173,13 @@ bool TSchedacdc_mask::on_field_event(TOperable_field& o, TField_event e, long jo
 					return error_box(TR("La data iniziale non pu� essere successiva alla data finale"));
 			}	  		
   	}
+    if (e == fe_close)
+    {
+      const int annoes = get_int(F_ANNO);
+      const TDate datafin = get(F_DATAFIN);
+      if (annoes == 0 && !datafin.ok())
+        return error_box(TR("Data finale obbligatoria se anno esercizio non specificato"));
+    }
   	break;	
   default: break;
   }  
@@ -556,6 +602,7 @@ void TSchedacdc::main_loop()
     }	
     else
     	ordin.insert("CODCMS|FASCMS|");
+
     TSorted_cursor sortcur (&relrmov, ordin, filtro, 2, &darec, &arec);
     sortcur.setregion(darec,arec);  
     sortcur.setfilter(filtro,TRUE);
@@ -575,6 +622,7 @@ void TSchedacdc::main_loop()
     _headercms = TRUE;
     _headerfsc = (ctrlfsc) ? TRUE : FALSE;
     _headersottoc = TRUE;
+
     for (sortcur=0; sortcur.pos()<num; ++sortcur)    //scansione su tutte le righe di movimento
     { 
     	const TRectype rmovrec = sortcur.curr();
@@ -583,8 +631,8 @@ void TSchedacdc::main_loop()
     	_currsottoc = rmovrec.get_long(RMV_SOTTOCONTO);
     	_currgruppo = rmovrec.get_int(RMV_GRUPPO);
     	_currconto = rmovrec.get_int(RMV_CONTO);
-  		TDate datareg = rmovrec.get_date(RMV_DATAREG);
-  		TImporto importo(rmovrec.get_char(RMV_SEZIONE), rmovrec.get_real(RMV_IMPORTO));
+
+      TImporto importo(rmovrec.get_char(RMV_SEZIONE), rmovrec.get_real(RMV_IMPORTO));
   		if ((_oldcms != _currcms) || (_oldfsc != _currfsc) || (_oldgruppo != _currgruppo) || (_oldconto != _currconto) || (_oldsottoc != _currsottoc))
     	{
         if (_oldgruppo > 0)
@@ -601,12 +649,19 @@ void TSchedacdc::main_loop()
 	  			if (_oldcms != _currcms)
 						print_footer_cms();
 				}
-			}	
-			aggiorna_totali(importo, datareg);
+			}
+      
+      TDate data;
+      if (_codes > 0)
+        data = relrmov.curr(LF_MOV).get_date(MOV_DATACOMP);
+      else
+        data = rmovrec.get_date(RMV_DATAREG);
 
-      bool da_stampare = !_dataini.ok() || datareg >= _dataini;
+			aggiorna_totali(importo, data);
+
+      bool da_stampare = !_dataini.ok() || data >= _dataini;
       if (da_stampare)
-        da_stampare = !_datafin.ok() || datareg <= _datafin;
+        da_stampare = !_datafin.ok() || data <= _datafin;
   		if ( da_stampare)
   			print_movimento(sortcur);
     } 
diff --git a/cm/cm0200a.frm b/cm/cm0200a.frm
index 5226e90ea..b35324226 100755
--- a/cm/cm0200a.frm
+++ b/cm/cm0200a.frm
@@ -8,7 +8,7 @@ BEGIN
   GRID ""
 END
 
-SECTION HEADER FIRST 6
+SECTION HEADER FIRST 7
 
 STRINGA 1 5
 BEGIN
@@ -87,6 +87,12 @@ BEGIN
    PROMPT 40 6 "a fase: "
 END
 
+STRINGA -1
+BEGIN
+  KEY "Intestazione stampa"
+  PROMPT 1 7 "____________________________________________________________________________________________________________________________________"
+END
+
 END // section header first
 
 // intestazione commessa
@@ -123,7 +129,7 @@ END
 
 END // section header last
 
-// intestazione vera e proprioa della stampa (a parte perch� va stampata o dopo la commessa e dopo la fase)
+// intestazione vera e propria della stampa (a parte perch� va stampata o dopo la commessa e dopo la fase)
 SECTION HEADER EVEN 4
 
 STRINGA -1
diff --git a/db/db1100.cpp b/db/db1100.cpp
index e6e8d674a..55ed385f6 100755
--- a/db/db1100.cpp
+++ b/db/db1100.cpp
@@ -328,11 +328,11 @@ inline TEsplosione_distinta_app& app() { return (TEsplosione_distinta_app&)main_
 ///////////////////////////////////////////////////////////////////
 // Callback & funzione per valorizzazione nodi
 ///////////////////////////////////////////////////////////////////
+
 static real valorizza_nodo(TDistinta_tree & node, _CallBackStruct & c)
 {
   TAssoc_array*    valori = c._a;
   TToken_string path;
-
   node.curr_id(path);
 	
 	real * valore = (real *) valori->objptr(path);
@@ -345,13 +345,12 @@ static real valorizza_nodo(TDistinta_tree & node, _CallBackStruct & c)
   TCodice_articolo codart;
 	TString16 liv;
 	TCodice_um um;
-	real qta = node.curr_qta();
-  TString& annoes  = pp->_anno_es;
-  TString& catven  = pp->_catven;
+  const TString& annoes = pp->_anno_es;
+  const TString& catven = pp->_catven;
 	TString16 codmag;
   TString& codlist = pp->_codlist;
 	const bool dettagliata = pp->_advanced_val;
-	bool valorizzato = FALSE;
+	bool valorizzato = false;
 	const char tipo = node.curr_type();
 	real  valore_un;
 			
@@ -368,16 +367,14 @@ static real valorizza_nodo(TDistinta_tree & node, _CallBackStruct & c)
 	if (dettagliata && tipo == 'A')
 	{
 		TArticolo_giacenza & art = TExplode_distinta_form::cache_articoli().art(codart);
-		const int art_tipo = art.get_int(ANAMAG_VALDIST);
+		const valtype art_tipo = (valtype)art.get_int(ANAMAG_VALDIST);
 
-		if (art_tipo > 0)
+		if (art_tipo > no_val)
 		{
 			const TDate inizio_val = art.get_date(ANAMAG_DATAVDIST);
-
 			if (pp->_obs_date >= inizio_val)
 			{
-				valorizzato = TRUE;
-				switch ((valtype) art_tipo)
+				switch (art_tipo)
 				{
 					case last_cost:      valore_un = art.ultimo_costo(annoes); break;
 					case last2cost:      valore_un = art.media_costi(annoes); break;
@@ -393,6 +390,7 @@ static real valorizza_nodo(TDistinta_tree & node, _CallBackStruct & c)
 				}
 				
 				valore_un = art.convert_to_um(valore_un, um);
+				valorizzato = true;
 			}
 		}
 	}
@@ -450,6 +448,7 @@ static real valorizza_nodo(TDistinta_tree & node, _CallBackStruct & c)
 		}
 	}
 	valori->add(path, valore_un);
+  const	real qta = node.last_qta(); // NON node.curr_qta();
 	const real valore_totale = valore_un * qta;
 	
 	return valore_totale;
diff --git a/ef/ef0300.cpp b/ef/ef0300.cpp
index f0fdc1e24..c73d9d221 100755
--- a/ef/ef0300.cpp
+++ b/ef/ef0300.cpp
@@ -397,6 +397,8 @@ bool TVariazione_distinte::user_create()
   _msk = new TMask("ef0300a");  
   _m2 = new TMask("ef0300c");
   _rel = new TRelation(LF_EFFETTI);
+	if (_rel->last() == NOERR)
+		_msk->set(F_TIPODIST, _rel->curr().get("TIPODIST"));
 
   _distinta = new TDistinta;  
   set_search_field(F_NUMBER);//setto il campo di ricerca della distinta
diff --git a/ef/ef0300a.uml b/ef/ef0300a.uml
index e33effcbc..0144d3dbd 100755
--- a/ef/ef0300a.uml
+++ b/ef/ef0300a.uml
@@ -30,6 +30,7 @@ BEGIN
   MESSAGE RESET,F_TIPOCF|DISABLE,F_TIPOCF
   ITEM "S|Allo sconto"
   MESSAGE RESET,F_TIPOCF|DISABLE,F_TIPOCF
+	FLAGS "P"
 END
 
 LIST F_NUMBERRIGA 12
diff --git a/include/alex.cpp b/include/alex.cpp
index aad9e9aa3..45f013b29 100755
--- a/include/alex.cpp
+++ b/include/alex.cpp
@@ -21,7 +21,7 @@ enum AVM_opcode
   avm_nop, 
   avm_add, avm_and, 
   avm_begin,
-  avm_call_word, avm_cold, avm_cr,
+  avm_call_word, avm_ceil, avm_cold, avm_cr,
   avm_cmp_eq, avm_cmp_gt, avm_cmp_gteq, avm_cmp_lt, avm_cmp_lteq, avm_cmp_noteq, 
   avm_cmp_emptyeq, avm_cmp_nulleq, avm_cmp_zeroeq,
   avm_div, avm_divide, avm_do, avm_dot, avm_drop, avm_dup, 
@@ -34,10 +34,10 @@ enum AVM_opcode
   avm_negate, avm_null,
   avm_or, avm_over, 
   avm_perform, avm_pick, avm_plus_loop, avm_plus_store, avm_push, 
-  avm_repeat, avm_rdrop, avm_rpeek, avm_rpush, avm_roll, avm_rot, 
+  avm_repeat, avm_rdrop, avm_rpeek, avm_rpush, avm_roll, avm_rot, avm_round,
   avm_strlen, avm_strmid, avm_strtok_fetch, avm_strtok_add, 
   avm_store, avm_sp, avm_sub, avm_swap, 
-  avm_then, 
+  avm_then, avm_trunc,
   avm_until, avm_usrword, 
   avm_variable,
   avm_warm, avm_while,
@@ -49,7 +49,7 @@ const char* AVM_TOKENS[avm_zzz+1] =
   "$NOP$",
   "+", "AND",
   "BEGIN",
-  "$CALL_WORD$", "COLD", "CR",
+  "$CALL_WORD$", "CEIL", "COLD", "CR",
   "=", ">", ">=", "<", "<=", "<>", 
   "EMPTY=", "NULL=", "0=", 
   "DIV", "/", "DO", ".", "DROP", "DUP",
@@ -62,10 +62,10 @@ const char* AVM_TOKENS[avm_zzz+1] =
   "NEGATE", "NULL",
   "OR", "OVER",
   "PERFORM", "PICK", "+LOOP", "+!", "$PUSH$",
-  "REPEAT", "R>", "R@", ">R", "ROLL", "ROT",
+  "REPEAT", "R>", "R@", ">R", "ROLL", "ROT", "ROUND",
   "STRLEN", "STRMID", "STRTOK@", "STRTOK+", 
   "!", "SP", "-", "SWAP",
-  "THEN", 
+  "THEN", "TRUNC",
   "UNTIL", "$USR$",
   "VARIABLE",
   "WARM", "WHILE"
@@ -781,6 +781,14 @@ void TAVM::execute(const TAVM_op& op)
     break;
   case avm_begin: break;
   case avm_call_word: do_call(op.var().as_string()); break;
+  case avm_ceil: 
+    {
+      const long dec = _stack.pop().as_int();
+      TVariant& v0 = (TVariant&)_stack.peek();
+      real k = v0.as_real(); k.ceil(dec);
+      v0 = k;
+    }
+    break;
   case avm_cold: do_restart(true); _bc = NULL; break;
   case avm_cr: _stack.push("\n"); break;
   case avm_cmp_eq   : _stack.push(compare_tos_nos() == 0); break;
@@ -935,6 +943,14 @@ void TAVM::execute(const TAVM_op& op)
   case avm_rpush: _rstack.push(_stack.pop()); break;
   case avm_roll: _stack.roll(_stack.pop().as_int()); break;
   case avm_rot: _stack.roll(2); break;
+  case avm_round: 
+    {
+      const long dec = _stack.pop().as_int();
+      TVariant& v0 = (TVariant&)_stack.peek();
+      real k = v0.as_real(); k.round(dec);
+      v0 = k;
+    }
+    break;
   case avm_store: do_store(_stack.pop().as_string()); break;
   case avm_strlen: _stack.push(_stack.peek().as_string().len()); break;
   case avm_strmid: 
@@ -971,6 +987,15 @@ void TAVM::execute(const TAVM_op& op)
     break;
   case avm_swap: _stack.roll(1); break;
   case avm_then: break;
+  case avm_trunc: 
+    {
+      const long dec = _stack.pop().as_int();
+      TVariant& v0 = (TVariant&)_stack.peek();
+      real k = v0.as_real(); k.trunc(dec);
+      v0 = k;
+    }
+    break;
+
   case avm_until: 
     if (_stack.pop().is_zero())
       _ip = op.var().as_int(); 
diff --git a/include/colors.h b/include/colors.h
index 040d1848b..84fa3c655 100755
--- a/include/colors.h
+++ b/include/colors.h
@@ -32,7 +32,9 @@ extern COLOR REQUIRED_BACK_COLOR;
 extern bool CAMPI_SCAVATI; 
 extern bool ADVANCED_GRAPHICS; 
 extern bool AUTOSELECT;
+extern bool AUTOZOOM;
 extern bool SMALL_ICONS;
+extern bool AUTOEND;
 
 const COLOR COLOR_DKCYAN = MAKE_COLOR(0,128,128);
 const COLOR COLOR_DKYELLOW = MAKE_COLOR(128,128, 0);
diff --git a/include/controls.cpp b/include/controls.cpp
index 4cfe7d3e3..28b0b382f 100755
--- a/include/controls.cpp
+++ b/include/controls.cpp
@@ -34,12 +34,14 @@ COLOR FOCUS_COLOR = NORMAL_COLOR;
 COLOR FOCUS_BACK_COLOR = COLOR_YELLOW;
 COLOR REQUIRED_BACK_COLOR = MAKE_COLOR(255,255,156);
 
-bool CAMPI_SCAVATI = TRUE;
-bool AUTOSELECT = FALSE;
-bool ADVANCED_GRAPHICS = TRUE;
-bool SMALL_ICONS=FALSE;
+bool CAMPI_SCAVATI = true;
+bool AUTOSELECT = false;
+bool ADVANCED_GRAPHICS = true;
+bool AUTOZOOM = false;
+bool SMALL_ICONS=false;
+bool AUTOEND = false;
 
-HIDDEN bool _button_blocked = FALSE;
+HIDDEN bool _button_blocked = false;
 HIDDEN int  _last_mouse_button = 0;
 HIDDEN TDropDownList* _cur_ddl = NULL;
 
@@ -103,9 +105,9 @@ bool TPicture_array::add(short id)
   {
 		if (SMALL_ICONS)
 		{
-			ignore_xvt_errors(TRUE);
+			ignore_xvt_errors(true);
 			i = new TImage(10000+id);
-			ignore_xvt_errors(FALSE);
+			ignore_xvt_errors(false);
 			if (!i->ok())
 				i->load(id);
 		}
@@ -231,7 +233,7 @@ XVT_FNTID xvt_load_default_font()
   }           
   
   X_FU_MULTIPLE = Y_FU_MULTIPLE = 0;
-  XVT_FNTID font =  xvt_default_font(FALSE);
+  XVT_FNTID font =  xvt_default_font(false);
   xi_set_font_id(font);
 	xi_init_sysvals();  // Ricalcola i FU units
 
@@ -273,6 +275,7 @@ void customize_colors()
   TOOL_BACK_COLOR = colors.get_color("ToolBack", NULL, -1, MASK_DARK_COLOR);
   CAMPI_SCAVATI = colors.get_bool("Campi3D", NULL, -1, CAMPI_SCAVATI);
   AUTOSELECT = colors.get_bool("AutoSelect", NULL, -1, AUTOSELECT);
+  AUTOZOOM = colors.get_bool("AutoZoom", NULL, -1, AUTOZOOM);
   ADVANCED_GRAPHICS = colors.get_bool("AdvancedGraphics", NULL, -1, ADVANCED_GRAPHICS);
   SMALL_ICONS = colors.get_bool("SmallIcons", NULL, -1, SMALL_ICONS);
   const int SPEECH_MODE = colors.get_int("SpeechMode", NULL, -1, 0);
@@ -302,12 +305,12 @@ void init_controls()
 {
   xi_set_font_id(xvt_load_default_font());
 
-  xi_set_pref(XI_PREF_NATIVE_CTRLS, FALSE);
-  xi_set_pref(XI_PREF_3D_LOOK,      TRUE);
+  xi_set_pref(XI_PREF_NATIVE_CTRLS, false);
+  xi_set_pref(XI_PREF_3D_LOOK,      true);
   xi_set_pref(XI_PREF_CARET_WIDTH,  2);
 #ifdef XI_R4
   xi_set_pref(XI_PREF_COMBO_ICON,     ICO_COMBO);
-  xi_set_pref(XI_PREF_OPTIMIZE_CELL_REQUESTS, TRUE);
+  xi_set_pref(XI_PREF_OPTIMIZE_CELL_REQUESTS, true);
 #else
   xi_set_pref(XI_PREF_COMBO_ICON,     COMBO_ICON);
 #endif
@@ -399,7 +402,7 @@ HIDDEN void init_fu_multiple(XI_OBJ* itf)
 
 HIDDEN XI_BITMAP* get_background_bitmap()
 {
-  static bool checked = FALSE;
+  static bool checked = false;
   static XI_BITMAP* bmp = NULL;
   
   if (ADVANCED_GRAPHICS)
@@ -410,7 +413,7 @@ HIDDEN XI_BITMAP* get_background_bitmap()
       TFilename back = ini.get("Tile");
       if (back.custom_path())
         bmp = xi_bitmap_create(back.get_buffer(), XI_BITMAP_TILE);
-      checked = TRUE;
+      checked = true;
     }
     return bmp;
   }
@@ -466,12 +469,12 @@ WINDOW create_interface(WINDOW parent, short x, short y, short dx, short dy,
   XI_OBJ_DEF* def = xi_create_itf_def(ITF_CID, xi_event_handler, (XinRect *) &r, (char*)caption, (long)msk);
   CHECK(def, "Can't define an interface");
 
-  def->v.itf->automatic_back_color = FALSE;
+  def->v.itf->automatic_back_color = false;
   def->v.itf->back_color = MASK_BACK_COLOR;
-  def->v.itf->font_id = xvt_default_font(FALSE);
-  def->v.itf->tab_on_enter = TRUE;
+  def->v.itf->font_id = xvt_default_font(false);
+  def->v.itf->tab_on_enter = true;
   def->v.itf->win = (XinWindow)win;
-  def->v.itf->edit_menu = TRUE;                 // Update edit menu items
+  def->v.itf->edit_menu = true;                 // Update edit menu items
   def->v.itf->menu_win = (XinWindow)TASK_WIN;   // Window that owns the menu
 
   XI_BITMAP* bmpback = get_background_bitmap();
@@ -538,9 +541,9 @@ void attach_interface(WINDOW win, COLOR back)
   XI_OBJ_DEF* def = xi_create_itf_def(ITF_CID, xi_event_handler, (XinRect *) &rc, caption, (long)parent);
   CHECK(def, "Can't define an interface");
 
-  def->v.itf->automatic_back_color = FALSE;
+  def->v.itf->automatic_back_color = false;
   def->v.itf->back_color = back;
-  def->v.itf->tab_on_enter = TRUE;
+  def->v.itf->tab_on_enter = true;
   def->v.itf->win = (XinWindow)win;
 
   XI_OBJ* itf = xi_create(NULL, def);
@@ -552,7 +555,7 @@ void attach_interface(WINDOW win, COLOR back)
 
 HIDDEN void xi_event_handler(XI_OBJ* itf, XI_EVENT* xiev)
 {
-  static bool notify_xvt = TRUE;
+  static bool notify_xvt = true;
 
   TControl* ctl = NULL;
 
@@ -618,10 +621,10 @@ HIDDEN void xi_event_handler(XI_OBJ* itf, XI_EVENT* xiev)
       if (w != NULL && w->win() != NULL_WIN)
         w->handler(w->win(), &xiev->v.xvte);
       if (xiev->v.xvte.type == E_MOUSE_UP)
-        _button_blocked = FALSE;
+        _button_blocked = false;
     }
     else
-      notify_xvt = TRUE;
+      notify_xvt = true;
     break;
   case a_post:
     {
@@ -647,10 +650,10 @@ HIDDEN void xi_event_handler(XI_OBJ* itf, XI_EVENT* xiev)
     const bool ok = ctl->event_handler(itf, xiev);
     if (!ok)
     {
-      xiev->refused = TRUE;
+      xiev->refused = true;
       if (xiev->type == XIE_CHAR_FIELD || xiev->type == XIE_CHAR_CELL ||
           xiev->type == XIE_XVT_EVENT)
-        notify_xvt = FALSE;
+        notify_xvt = false;
     }
   }
 }
@@ -777,16 +780,16 @@ void TControl::update_tab_cid()
 {                            
   const bool is_cont = is_container(_obj);
   
-  XI_OBJ *first = find_operable(_obj->itf, TRUE, !is_cont);
+  XI_OBJ *first = find_operable(_obj->itf, true, !is_cont);
   set_tab_cid(_obj, first->cid);
   
-  XI_OBJ *last = find_operable(_obj->itf, FALSE, !is_cont);
+  XI_OBJ *last = find_operable(_obj->itf, false, !is_cont);
   set_tab_cid(last, _obj->cid);
 
   if (is_cont)
   {
-    XI_OBJ* fi = find_operable(_obj->itf, TRUE,  TRUE);
-    XI_OBJ* la = find_operable(_obj->itf, FALSE, TRUE);
+    XI_OBJ* fi = find_operable(_obj->itf, true,  true);
+    XI_OBJ* la = find_operable(_obj->itf, false, true);
     int num; 
     XI_OBJ** child = xi_get_member_list(_obj, &num);
     set_tab_cid(child[num-1], fi->cid);
@@ -794,8 +797,8 @@ void TControl::update_tab_cid()
   } else 
   if (_obj->parent != _obj->itf)
   {
-    XI_OBJ* fi = find_operable(_obj->itf, TRUE,  FALSE);
-    XI_OBJ* la = find_operable(_obj->itf, FALSE, FALSE);
+    XI_OBJ* fi = find_operable(_obj->itf, true,  false);
+    XI_OBJ* la = find_operable(_obj->itf, false, false);
     set_tab_cid(_obj->parent, fi->cid);
     set_tab_cid(la, _obj->parent->cid);
   }
@@ -896,7 +899,7 @@ RCT& TControl::get_rect(RCT& r) const
 
 void TControl::set_rect(const RCT& r)
 {
-  xi_set_rect(_obj, (XinRect*)&r, FALSE);
+  xi_set_rect(_obj, (XinRect*)&r, false);
 }
 
 unsigned long TControl::flags2attr(const char* flags) const
@@ -919,7 +922,7 @@ unsigned long TControl::flags2attr(const char* flags) const
 
 const char* TControl::parse_caption(const char* cap, bool& bold, COLOR& color) const
 {
-  bold = FALSE;
+  bold = false;
   color = NORMAL_COLOR;
   
   const char* t;
@@ -931,7 +934,7 @@ const char* TControl::parse_caption(const char* cap, bool& bold, COLOR& color) c
       const char code = toupper(*(t+1));
       if (code == 'B')
       {
-        bold = TRUE;
+        bold = true;
         t++;
       }
       else
@@ -980,7 +983,7 @@ void TControl::set_focus() const
 
 bool TControl::notify_key(KEY k)
 {
-  bool ok = TRUE;
+  bool ok = true;
 
   if (_fld == NULL)
   {
@@ -1007,7 +1010,7 @@ bool TControl::is_edit_key(KEY k) const
 
 bool TControl::event_handler(XI_OBJ* itf, XI_EVENT* xiev)
 {
-  bool ok = TRUE;
+  bool ok = true;
   return ok;
 }
 
@@ -1046,8 +1049,8 @@ void TControl::change_attrib(unsigned long mask, bool on, XI_OBJ* obj)
 // @mfunc Mostra/Nasconde il controllo
 void TControl::show(
      bool on)  // @parm Operazione da svolgere sul controllo:
-         // @flag TRUE | Il controllo viene mostrato
-         // @flag FALSE | Il controllo viene nascosto
+         // @flag true | Il controllo viene mostrato
+         // @flag false | Il controllo viene nascosto
 {
   change_attrib(XI_ATR_VISIBLE, on);
 }
@@ -1057,8 +1060,8 @@ void TControl::show(
 // @mfunc Abilita/disabilita il controllo
 void TControl::enable(
      bool on)  // @parm Operazione da svolgere sul controllo:
-         // @flag TRUE | Il controllo viene abilitato
-         // @flag FALSE | Il controllo viene disabilitato
+         // @flag true | Il controllo viene abilitato
+         // @flag false | Il controllo viene disabilitato
 {
   change_attrib(XI_ATR_ENABLED, on);
 }
@@ -1121,7 +1124,7 @@ TText_control::TText_control(WINDOW win, short cid,
   CHECKS(def, "Can't create the definition of TText_control:", text);
   def->v.text->fore_color = color;
   if (bold)
-    def->v.text->font_id = xvt_default_font(TRUE);
+    def->v.text->font_id = xvt_default_font(true);
   _obj = xi_create(get_interface(win), def);
   CHECKS(_obj, "Can't create TText_control ", text);
 
@@ -1186,8 +1189,8 @@ TGroupbox_control::TGroupbox_control(WINDOW win, short cid,
   const bool erre = strchr(flags, 'R') != NULL;
   if (erre)
   {
-    def->v.rect->well = TRUE;                  // Mette in rilievo il rettangolo
-    change_attrib(XI_ATR_RJUST, FALSE, _obj);  // Toglie l'erroneo allineamento a destra del titolo
+    def->v.rect->well = true;                  // Mette in rilievo il rettangolo
+    change_attrib(XI_ATR_RJUST, false, _obj);  // Toglie l'erroneo allineamento a destra del titolo
   }
   _rct = xi_create(get_interface(win), def);
   CHECKD(_rct, "Can't create Groupbox_control ", cid);
@@ -1216,7 +1219,7 @@ RCT& TGroupbox_control::get_rect(RCT& r) const
 // TField
 ///////////////////////////////////////////////////////////
 
-static bool in_create = FALSE;
+static bool in_create = false;
 
 TField_control::TField_control(WINDOW win, short cid,
                                short left, short top, short width, short maxlen,
@@ -1230,7 +1233,7 @@ void TField_control::create(WINDOW win, short cid,
                        short left, short top, short width, short height, short maxlen,
                        const char* flags, const char* text, bool button)
 {
-  in_create = TRUE;
+  in_create = true;
 
   const short fcid = cid > 0 ? cid + 2000 : cid - 2000;
   XI_OBJ_DEF* frm_def = xi_add_form_def(NULL, fcid, fcid);
@@ -1242,6 +1245,8 @@ void TField_control::create(WINDOW win, short cid,
   unsigned long attrib = flags2attr(flags) | XI_ATR_EDITMENU;
   if (AUTOSELECT) 
     attrib |= XI_ATR_AUTOSELECT;
+  if (AUTOEND) 
+    attrib |= XI_AGA_ATR_AUTOEND;
   if (!CAMPI_SCAVATI)
     attrib |= XI_ATR_BORDER;
   if (maxlen > width)
@@ -1262,10 +1267,10 @@ void TField_control::create(WINDOW win, short cid,
 
   if (height == 1)
   {
-    f->auto_tab = TRUE;
+    f->auto_tab = true;
     if (button)
     {
-      f->button = TRUE;
+      f->button = true;
       f->pixel_button_distance = 1;
     }
   }
@@ -1275,8 +1280,8 @@ void TField_control::create(WINDOW win, short cid,
     f->xi_rct.bottom = rct.bottom;
     f->xi_rct.right = rct.right;
     f->xi_rct.left = rct.left;
-    f->cr_ok = TRUE;
-    f->var_len_text = TRUE;
+    f->cr_ok = true;
+    f->var_len_text = true;
   }
 
   XI_OBJ* itf = get_interface(win);
@@ -1301,7 +1306,7 @@ void TField_control::create(WINDOW win, short cid,
   xi_dequeue();
   xi_tree_free(frm_def);
 
-  in_create = FALSE;
+  in_create = false;
 }
 
 void TField_control::show_button(bool on)
@@ -1328,9 +1333,9 @@ void TField_control::set_read_only(bool on)
 bool TField_control::event_handler(XI_OBJ* itf, XI_EVENT* xiev)
 {
   if (in_create)
-    return FALSE;
+    return false;
 
-  bool ok = TRUE;
+  bool ok = true;
 
   switch(xiev->type)
   {
@@ -1349,7 +1354,7 @@ bool TField_control::event_handler(XI_OBJ* itf, XI_EVENT* xiev)
       if (k == K_PREV || k == K_NEXT || k > K_CTRL)
       {
         k = K_TAB;
-        xiev->refused = TRUE;
+        xiev->refused = true;
       }  
       if (k == K_TAB || is_edit_key(k) || (k > K_F1 && k < K_F12))
         ok = notify_key(k);
@@ -1386,7 +1391,7 @@ TMultiline_control::TMultiline_control(WINDOW win, short cid,
                                        short width, short height, short maxlen,
                                        const char* flags, const char* text)
 {
-  create(win, cid, left, top, width, height, maxlen, flags, text, FALSE);
+  create(win, cid, left, top, width, height, maxlen, flags, text, false);
 }
 
 ///////////////////////////////////////////////////////////
@@ -1482,7 +1487,7 @@ void TButton_control::check(bool on)
 
 bool TButton_control::checked() const
 {
-  return xi_is_checked(_obj) ? TRUE : FALSE;
+  return xi_is_checked(_obj) ? true : false;
 }
 
 bool TButton_control::toggle()
@@ -1494,14 +1499,14 @@ bool TButton_control::toggle()
 
 bool TButton_control::event_handler(XI_OBJ* itf, XI_EVENT* xiev)
 {
-  bool ok = TRUE;
+  bool ok = true;
 
   if (xiev->type == XIE_BUTTON)
   {
     if (_last_mouse_button == 0)
     {                           
       if (id() != DLG_CANCEL && id() != DLG_QUIT) 
-        ok = xi_move_focus(_obj) ? TRUE : FALSE;
+        ok = xi_move_focus(_obj) ? true : false;
        
       if (ok) 
       {
@@ -1561,7 +1566,7 @@ void TPushbutton_control::set_caption(const char* c)
     TControl::set_caption(cap);
     set_central_icon(0);
     set_bmp(0, 0);
-    _obj->v.btn->drawable = FALSE;
+    _obj->v.btn->drawable = false;
     _obj->v.btn->fore_color = color;
   }
 }
@@ -1571,7 +1576,7 @@ void TPushbutton_control::set_central_icon(unsigned int hicon)
   xi_set_icon(_obj, hicon, hicon);
   _obj->v.btn->icon_x = (_obj->v.btn->rct.right - _obj->v.btn->rct.left - 32) / 2 - 5;
   _obj->v.btn->icon_y = (_obj->v.btn->rct.bottom - _obj->v.btn->rct.top - 32) / 2 - 5;
-  _obj->v.btn->drawable = FALSE;
+  _obj->v.btn->drawable = false;
 }
 
 void TPushbutton_control::set_bmp(short bmp_up, short bmp_dn)
@@ -1792,7 +1797,7 @@ void TRadiobutton_control::check_button(byte c)
   XI_OBJ** child = xi_get_member_list(_obj, &children);
   CHECKD(c < children, "This radio is rather old, it doesn't have button ", c);
   if (!xi_is_checked(child[c]))
-    xi_check(child[c], TRUE);
+    xi_check(child[c], true);
 }
 
 void TRadiobutton_control::show_button(byte c, bool on)
@@ -1805,7 +1810,7 @@ void TRadiobutton_control::show_button(byte c, bool on)
 
 bool TRadiobutton_control::event_handler(XI_OBJ* itf, XI_EVENT* xiev)
 {
-  bool ok = TRUE;
+  bool ok = true;
   if (xiev->type == XIE_BUTTON)
   {
     XI_OBJ* obj = xiev->v.xi_obj;       // Elemento del gruppo di radio buttons da premere
@@ -1813,12 +1818,12 @@ bool TRadiobutton_control::event_handler(XI_OBJ* itf, XI_EVENT* xiev)
     {
       if (!xi_is_checked(obj))          // Se non e' gia' premuto ...
       {
-        xi_check(obj, TRUE);            // ... allora premilo e ...
+        xi_check(obj, true);            // ... allora premilo e ...
         ok = notify_key(K_SPACE);       // ... avverti il mask_field proprietario
       }
     }
     else
-      ok = FALSE;
+      ok = false;
   }
   else
     ok = TButton_control::event_handler(itf, xiev);
@@ -1882,7 +1887,7 @@ TTagbutton_control::TTagbutton_control(WINDOW win, short cid,
 
 bool TTagbutton_control::event_handler(XI_OBJ* itf, XI_EVENT* xiev)
 {                         
-  bool ok = TRUE;    
+  bool ok = true;    
   if (xiev->type == XIE_BUTTON)
   {                          
     XI_OBJ* obj = xiev->v.xi_obj;        // Elemento del gruppo di radio buttons da premere
@@ -1973,7 +1978,7 @@ void TDropDownList::ddl_str_eh(XI_OBJ* itf, XI_EVENT* xiev)
          xiev->v.rec_request.data_rec = n;
        }
        else
-         xiev->refused = TRUE;
+         xiev->refused = true;
        break;
      case XIE_GET_LAST:
        xiev->v.rec_request.data_rec = ddl->items() - 1;
@@ -1986,7 +1991,7 @@ void TDropDownList::ddl_str_eh(XI_OBJ* itf, XI_EVENT* xiev)
          if (n >= 0 && n < ddl->items())
            xiev->v.rec_request.data_rec = n;
          else
-           xiev->refused = TRUE;
+           xiev->refused = true;
        }
        break;
      case XIE_CELL_REQUEST:
@@ -2049,9 +2054,9 @@ void TDropDownList::close()
 {
   if (_open)
   {
-    _open = FALSE;
+    _open = false;
     if (_xi_lst != NULL)
-      xvt_vobj_set_visible((WINDOW)xi_get_window(_xi_lst->itf), FALSE);
+      xvt_vobj_set_visible((WINDOW)xi_get_window(_xi_lst->itf), false);
     _cur_ddl = NULL;
   }
 }
@@ -2085,10 +2090,10 @@ bool TDropDownList::select(int i, bool force)
     if (force && _open)
       xi_scroll_rec(_xi_lst, i, FOCUS_COLOR, XI_ATR_ENABLED | XI_ATR_SELECTED, 0);
  
-    return TRUE;
+    return true;
   }
 
-  return FALSE;
+  return false;
 }
 
 bool TDropDownList::select_by_initial(char c)
@@ -2096,7 +2101,7 @@ bool TDropDownList::select_by_initial(char c)
   const int tot = _values.items();
   int i = _selected;
   c = toupper(c);
-  while(TRUE)
+  while(true)
   {
     i++;
     if (i >= tot) 
@@ -2108,7 +2113,7 @@ bool TDropDownList::select_by_initial(char c)
       break;
   }
 
-  bool ok = FALSE;
+  bool ok = false;
   if (i != selected())
   {                                
     if (is_open())
@@ -2139,7 +2144,7 @@ bool TDropDownList::select_by_ofs(int i)
   i += _selected;
   if (i >= 0 && i < _values.items())
     return select(i);
-  return FALSE;
+  return false;
 }
 
 void TDropDownList::set_values(const char* c, const char* v)
@@ -2173,7 +2178,7 @@ void TDropDownList::create()
   
   XI_OBJ_DEF* itfdef = xi_create_itf_def(ITF_CID+1, (XI_EVENT_HANDLER)ddl_str_eh, NULL, "",
                                          (long)this);
-  itfdef->v.itf->automatic_back_color = TRUE;
+  itfdef->v.itf->automatic_back_color = true;
   
   const int hei = items() <= 1 ? 2*XI_FU_MULTIPLE + 1 : (min(8,items()) * XI_FU_MULTIPLE) + 1;
   XI_OBJ_DEF* lstdef = xi_add_list_def(itfdef, _obj->cid+1000, 0, 0, hei,
@@ -2184,13 +2189,13 @@ void TDropDownList::create()
   XI_LIST_DEF* ld = lstdef->v.list;
   ld->active_back_color = FOCUS_BACK_COLOR;
   ld->scroll_bar = items() > 8;
-  ld->no_heading = TRUE;
-  ld->no_horz_lines = TRUE;
-  ld->no_vert_lines = TRUE;
-  ld->resize_with_window = TRUE;
-  ld->single_select = TRUE;
+  ld->no_heading = true;
+  ld->no_horz_lines = true;
+  ld->no_vert_lines = true;
+  ld->resize_with_window = true;
+  ld->single_select = true;
 #ifdef LINUX
-  ld->scroll_on_thumb_track = TRUE;
+  ld->scroll_on_thumb_track = true;
 #endif
   
   // compute size in pixel of field (with button enclosed)
@@ -2269,18 +2274,18 @@ void TDropDownList::open()
     return;
 
   if (_xi_lst != NULL)
-    xvt_vobj_set_visible((WINDOW)xi_get_window(_xi_lst->itf), TRUE);
+    xvt_vobj_set_visible((WINDOW)xi_get_window(_xi_lst->itf), true);
   else
     create();
   
-  _open = TRUE;
+  _open = true;
   xi_cell_request(_xi_lst);
 
   WINDOW win = (WINDOW)xi_get_window(_xi_lst->itf);
   xvt_scr_set_focus_vobj(win);
   xvt_vobj_raise(win);
 
-  select(_selected, TRUE);
+  select(_selected, true);
 
   xi_dequeue();
   _cur_ddl = this;
@@ -2290,7 +2295,7 @@ void TDropDownList::open()
 
 bool TListbox_control::event_handler(XI_OBJ* itf, XI_EVENT* xiev)
 {
-  bool ok = TRUE;
+  bool ok = true;
   switch (xiev->type)
   {
     case XIE_DBL_FIELD:
@@ -2316,7 +2321,7 @@ bool TListbox_control::event_handler(XI_OBJ* itf, XI_EVENT* xiev)
           _ddl->select_by_ofs(-1);                                      
         else if (k == K_F2 || k == K_F11 || k == K_F12)
           notify_key(k);
-        xiev->refused = TRUE;
+        xiev->refused = true;
       }
       break;
     case XIE_CHG_FIELD:
@@ -2346,7 +2351,7 @@ void TDropDownList::on_mouse_down(const PNT& pt)
 
 TDropDownList::TDropDownList(XI_OBJ* o, const char* codes, const char* values)
   : _obj(o), _xi_lst(NULL), _codes(codes),
-    _values(values), _selected(0), _open(FALSE)
+    _values(values), _selected(0), _open(false)
 {                       
   if (o->type == XIT_CELL)
   {
@@ -2370,9 +2375,9 @@ void TListbox_control::set_values(const char* cod, const char* val)
 {
   _ddl->set_values(cod, val);
   if (selected() >= items())
-    _ddl->select(0, TRUE);
+    _ddl->select(0, true);
   else
-    _ddl->select(selected(), TRUE);
+    _ddl->select(selected(), true);
 }
 
 int TListbox_control::items() const             
@@ -2405,9 +2410,9 @@ TListbox_control::TListbox_control(WINDOW win, short cid,
                                    const char* flags, const char* text,
                                    const char* codes, const char* values)
 {
-  create(win, cid, left, top, width , 1, width, flags, text, TRUE);
+  create(win, cid, left, top, width , 1, width, flags, text, true);
   _ddl = new TDropDownList(_obj, codes, values);
-  _ddl->select(0, TRUE);
+  _ddl->select(0, true);
 }
 
 TListbox_control::~TListbox_control()
diff --git a/include/dongle.cpp b/include/dongle.cpp
index e1ff80a2e..722b3bdb5 100755
--- a/include/dongle.cpp
+++ b/include/dongle.cpp
@@ -442,15 +442,16 @@ bool TDongle::eutron_login(bool test_all_keys)
 
 bool TDongle::network_login(bool test_all_keys)
 {
+  const char* appname = main_app().name();
+
   if (network() && ok())
-    rpc_UserLogout();
+    rpc_UserLogout(appname);
       
   TConfig ini(CONFIG_INSTALL, "Server");
   const char* server = ini.get("Dongle");
 //  const char* guest  = "******";
 //  const TString16 appname = main_app().name();
 //  const char* utente = (!main_app().is_running() && appname == "ba0100") ? guest : (const char *) user();
-  const char* appname = main_app().name();
   const char* utente = user();
 
   const bool ok = rpc_UserLogin(server, utente, "******", appname);
@@ -560,7 +561,7 @@ bool TDongle::logout()
       xvt_dongle_sl_logout(); 
       break;
     case _dongle_network:
-      rpc_UserLogout();
+      rpc_UserLogout(main_app().name());
       break;
     default:
       break;  
diff --git a/include/execp.cpp b/include/execp.cpp
index 5d28d04a1..ef7d535a9 100755
--- a/include/execp.cpp
+++ b/include/execp.cpp
@@ -38,6 +38,15 @@ long TExternal_app::run(
     if (!our_app)
       utente = FALSE;
   }  
+
+  if (*comm_name.ext() == '\0')
+    comm_name.ext("exe");
+  if (comm_name.custom_path() && p > 0)
+  {
+    path = comm_name;
+    path << _path.mid(p);
+  }
+
   if (utente)
     path << " /u" << user();
   
@@ -45,13 +54,16 @@ long TExternal_app::run(
   DIRECTORY oldir;
   xvt_fsys_get_dir(&oldir);
 
-  const TFilename dir(comm_name.path()); 
-  if (dir.not_empty())
+  if (!utente) // cambio directory se eseguo un programma estero
   {
-    DIRECTORY d;
-    if (xvt_fsys_convert_str_to_dir((char*)(const char*)dir, &d))
-      xvt_fsys_set_dir(&d);
-  }                
+    const TFilename dir(comm_name.path()); 
+    if (dir.not_empty() && dir.find("custom") < 0)
+    {
+      DIRECTORY d;
+      if (xvt_fsys_convert_str_to_dir((char*)(const char*)dir, &d))
+        xvt_fsys_set_dir(&d);
+    }                
+  }
   
   if (!async)
   {
diff --git a/include/isam.cpp b/include/isam.cpp
index 0250a8130..c3581a2ea 100755
--- a/include/isam.cpp
+++ b/include/isam.cpp
@@ -3340,6 +3340,16 @@ void TRectype::put_str(const char* fieldname, const char* val)
   setempty(FALSE);
 }
 
+void TRectype::add(const char* fieldname, const real& val)
+{
+  if (!val.is_zero())
+  {
+    real k = get_real(fieldname);
+    k += val;
+    put(fieldname, k);
+  }
+}
+
 void TRectype::zero(const char* fieldname)
 {
   if (*_tab && strcmp(fieldname , "COD") == 0)
diff --git a/include/isam.h b/include/isam.h
index cf22daaf7..6abf89edd 100755
--- a/include/isam.h
+++ b/include/isam.h
@@ -206,6 +206,8 @@ public:
   void put(const char* fieldname, long double val) 
   { put(fieldname, real(val)); }
 #endif
+  // @cmember Incrementa il contenuto del campo <p fieldname> in formato reale
+  void add(const char* fieldname, const real& val);
 
   // @cmember Vuota il campo puntato da <p fieldname>
   virtual void zero(const char * fieldname);
@@ -762,7 +764,7 @@ class TRecfield : public TObject
 // @access:(INTERNAL) Private Member
 {
   // @cmember:(INTERNAL) Nome del campo
-  char _name[30];
+  char _name[32];
   // @cmember:(INTERNAL) Puntatore a inizio record
   TRectype* _rec;
   // @cmember:(INTERNAL) Puntatore a inizio campo
@@ -815,19 +817,17 @@ public:
   TRecnotype ptr() const;
 
   // @cmember Ritorna un puntatore all'inizio del campo nel record. Dovrebbe essere protected!
-  const char* pos() const 
-  { return (const char*) _p;}
+  const char* pos() const { return (const char*) _p;}
+  // @cmember Ritorna il nome del campo
+  const char* name() const { return _name; }
   // @cmember Ritorna la lunghezza del campo
-  int len() const 
-  { return (int) _len;}
+  int len() const { return (int) _len;}
   // @cmember Ritorna il numero di decimali del campo
   int dec() const { return (int) _dec;} 
-  TFieldtypes type() const 
   // @cmember Ritorna il tipo del campo
-  { return _type;}
+  TFieldtypes type() const { return _type;}
   // @cmember Ritorna il puntatore a inizio record
-  TRectype& record() const 
-  { return *_rec;}
+  TRectype& record() const { return *_rec;}
 
   // @cmember Costruttore
   TRecfield(TRectype& rec, const char* name, int from = 0, int to = -1);
diff --git a/include/isamrpc.cpp b/include/isamrpc.cpp
index b651038f3..2e8a49756 100755
--- a/include/isamrpc.cpp
+++ b/include/isamrpc.cpp
@@ -302,12 +302,12 @@ bool rpc_UserLogin(const char* server, const char* user,
   return _connection != 0;
 }
 
-bool rpc_UserLogout()
+bool rpc_UserLogout(const char* appname)
 {   
   if (_connection)                                
   {                  
 		const int session = xvt_sys_get_session_id();
-    _rpc_call.format("UserLogout(%s, %d)", (const char*)user(), session);
+    _rpc_call.format("UserLogout(%s, %d, %s)", (const char*)user(), session, appname);
     rpc_Call(_rpc_call);
     _client->RemoveConnection(_connection);
     _connection = 0;
diff --git a/include/isamrpc.h b/include/isamrpc.h
index f861893b2..3ebe7922b 100755
--- a/include/isamrpc.h
+++ b/include/isamrpc.h
@@ -19,7 +19,7 @@ unsigned    rpc_DongleYear();
 
 bool        rpc_UserLogin(const char* server, const char* user, 
                           const char* password, const char* application);
-bool        rpc_UserLogout();  
+bool        rpc_UserLogout(const char* appname);  
 
 bool        rpc_Start();
 bool        rpc_Stop();
diff --git a/include/maskfld.cpp b/include/maskfld.cpp
index 07582abe5..8abf0255e 100755
--- a/include/maskfld.cpp
+++ b/include/maskfld.cpp
@@ -1,6 +1,7 @@
 #define XI_INTERNAL           
 #include <xinclude.h>
 
+#include <automask.h>
 #include <colors.h>
 #include <controls.h>
 #include <diction.h>
@@ -4836,9 +4837,39 @@ void TZoom_field::create(WINDOW parent)
   TEdit_field::create(parent);
 }
 
+class TZoom_mask : public TAutomask
+{
+
+protected:
+	virtual bool on_field_event(TOperable_field& o, TField_event e, long jolly);
+
+public:
+  TZoom_mask(const char * prompt);
+  virtual ~TZoom_mask() {}
+};
+
+bool TZoom_mask::on_field_event(TOperable_field& o, TField_event e, long jolly)
+{ 
+	return true;
+}
+
+TZoom_mask::TZoom_mask(const char * prompt) : TAutomask("Zoom", 1, 72, 18)
+{
+	const bool select = AUTOSELECT;
+	AUTOSELECT = false;
+	AUTOEND = true;
+	add_memo(101, 0, prompt, 1, 0, -1, -3);
+	add_button(DLG_OK,     0, "", -12, -1, 10, 2);
+	add_button(DLG_CANCEL, 0, "", -22, -1, 10, 2);
+	AUTOEND = false;
+	AUTOSELECT = select;
+	set_handlers();
+}
+
 bool TZoom_field::on_key( KEY key )
 { 
-  switch (key)
+  static KEY __k = '\0';
+	switch (key)
   {
   case K_TAB:
     if (focusdirty())
@@ -4848,22 +4879,42 @@ bool TZoom_field::on_key( KEY key )
     if (browse() != NULL)
       break;
   case K_F8:  
-  {
-    get_window_data();
-    TMask m("Zoom", 1, 72, 18);
-    m.add_memo(101, 0, prompt(), 1, 0, -1, -3);
-    m.add_button(DLG_OK,     0, "", -12, -1, 10, 2);
-    m.add_button(DLG_CANCEL, 0, "", -22, -1, 10, 2);
-    m.set(101, _str);
-    if (m.run() == K_ENTER)
-    {
-      _str = m.get(101);
-      set_window_data(raw2win(_str));
-    }
-    return TRUE;
-  }
-    break;
+		{
+			get_window_data();
+			TZoom_mask m(prompt());
+
+			if (__k)
+			{
+				_str << (const char) __k;
+				__k = '\0';
+			}
+			m.set(101, _str);
+
+			if (m.run() == K_ENTER)
+			{
+				_str = m.get(101);
+				set_window_data(raw2win(_str));
+			}
+			return TRUE;
+		}
+	  break;
   default:
+		if (AUTOZOOM && isalnum(key))
+		{
+			get_window_data();
+			if (_str.len() >= size())
+			{
+				__k = key;
+				if (mask().is_running())
+					on_key(K_F8);
+				else
+				{
+					TSheet_field * s = mask().get_sheet();
+					if (s != NULL)
+						dispatch_e_char(s->mask().win(), K_F8);
+				}
+			}
+		}
     break;
   }  
   return TEdit_field::on_key(key);  
diff --git a/include/modaut.h b/include/modaut.h
index 7421adb5c..16a0d683e 100755
--- a/include/modaut.h
+++ b/include/modaut.h
@@ -17,7 +17,7 @@
 #define SCAUT 13
 #define SRAUT 14
 #define CMAUT 15
-#define M73AUT 16
+#define LIAUT 16
 #define ATAUT 17
 #define INAUT 18
 #define POAUT 19
diff --git a/include/msksheet.cpp b/include/msksheet.cpp
index 58b9ac18f..8535edc4c 100755
--- a/include/msksheet.cpp
+++ b/include/msksheet.cpp
@@ -1626,6 +1626,8 @@ bool TSpreadsheet::event_handler(XI_OBJ* itf, XI_EVENT *xiev)
             owner().mask().notify_focus_field(owner().dlg());
             refused = TRUE;
           }
+					else 
+						refused = true;
           break;        
         case K_CTRL + 'A':
           {
@@ -1702,10 +1704,19 @@ bool TSpreadsheet::event_handler(XI_OBJ* itf, XI_EVENT *xiev)
           {     
             refused = TRUE;
           } else
-          if (is_edit_key(k) && !_edit_field->on_key(k)) 
-          {
-            refused = TRUE;
-            beep();
+	        if (is_edit_key(k))
+					{
+						if (AUTOZOOM)
+						{
+							if ((_edit_field->class_id() == CLASS_ZOOM_FIELD))
+								copy_cell2field();
+						}
+
+	          if (!_edit_field->on_key(k)) 
+		        {
+	            refused = true;
+		          beep();
+						}
           } else 
           if (_edit_field->is_kind_of(CLASS_LIST_FIELD))
           {      
@@ -1734,7 +1745,7 @@ bool TSpreadsheet::event_handler(XI_OBJ* itf, XI_EVENT *xiev)
             }
             refused = TRUE;
           }
-          break;
+      break;
       }
     }  
     break;
diff --git a/include/printer.cpp b/include/printer.cpp
index bd7d81ff2..5effab11e 100755
--- a/include/printer.cpp
+++ b/include/printer.cpp
@@ -885,7 +885,8 @@ const char* TPrintrow::row_codified() const
   int last_color = -1;
   int k = 0, i = 0, len = 0;     
 
-  char* tmp = get_tmp_string(256).get_buffer();
+  const int kmax = 1024;
+  char* tmp = get_tmp_string(kmax).get_buffer();
   
   // Calcolo lunghezza stringa
   for (i = _row.size()-1; i >= 0; i--)
@@ -939,6 +940,7 @@ const char* TPrintrow::row_codified() const
       tmp[k++] = '@';  //  Escape for @
     tmp[k++] = _row[i];
   }
+  CHECKD(k < kmax, "Internal buffer overflow ", k);
   tmp[k] = '\0';
   
   if (_images)
@@ -1482,7 +1484,7 @@ bool TPrinter::printrow(
                                          _printertype == exportprinter) ? 
                                          rowtoprint->row_codified () :
                                          rowtoprint->row ()));
-  rw.rtrim ();
+  rw.rtrim();
 
   int lun = rw.len ();
   int idx;
diff --git a/include/recset.cpp b/include/recset.cpp
index 0cb9dc391..aeab4bcb5 100755
--- a/include/recset.cpp
+++ b/include/recset.cpp
@@ -426,7 +426,9 @@ const TVariant& TRecordset::get_var(const char* name) const
 {
   // Se mi accorgo che posso e voglio accedere ad un campo del recordset padre
   if (_parentset != NULL && strncmp(name, "#PARENT.", 8) == 0) 
+  {
     return _parentset->get(name+8); // Attenzione! E' giusto usare get() e non get_var()
+  }
 
   const TVariant* var = (const TVariant*)_var.objptr(name);
   return var != NULL ? *var : NULL_VARIANT;
@@ -477,7 +479,7 @@ void TRecordset::find_and_reset_vars()
     if (is_var_separator(sql[diesis-1])) // Controllo che ci sia un separatore prima del #
     {
       int i = diesis+1;
-      for ( ; sql[i] && (isalnum(sql[i]) || sql[i] == '_' || sql[i] == '.'); i++);
+      for ( ; sql[i] && (isalnum(sql[i]) || sql[i] == '_' || sql[i] == '.' || sql[i] == '#'); i++);
       if (i > diesis+1)
       {
         const TString& name = sql.sub(diesis, i);
@@ -490,6 +492,10 @@ void TRecordset::find_and_reset_vars()
 void TRecordset::parsed_text(TString& sql) const
 {
   sql = query_text();
+  const bool is_isam = sql.starts_with("US");
+  const bool is_sql = !is_isam;
+  const char* apici = is_isam ? "\"" : "'";
+
   const bool vars = ((TSQL_recordset*)this)->ask_variables(false);
   if (vars) // Se ci sono variabili faccio le sostituzioni
   {
@@ -509,16 +515,19 @@ void TRecordset::parsed_text(TString& sql) const
         else
         {
           s = var.as_string();
-          for (int i = 0; s[i]; i++)
+          if (is_sql) // Raddoppia gli apici in SQL
           {
-            if (s[i] == '\'')
-              s.insert("'", i++);
+            for (int i = 0; s[i]; i++)
+            {
+              if (s[i] == '\'')
+                s.insert("'", i++);
+            }
           }
         }
-        if ((var.is_string() && s[0] != '\'') || var.is_null())
+        if ((var.is_string() && s[0] != *apici && sql.right(1) != apici) || var.is_null())
         {
-          s.insert("'");
-          s << '\'';
+          s.insert(apici);
+          s << apici;
         }
         sql << s << after;
       }
@@ -1224,11 +1233,13 @@ class TCursor_parser
 
 protected:
   const TString& pop();
+  const TString& line();
   void push();
   void add_column_info(const char* table, const TRectype& rec);
 
   void parse_sortexpr(TToken_string& se);
   void parse_filter(TToken_string& filter);
+  void parse_select(TToken_string& filter);
   void parse_region(TRectype& rec);
   void parse_join_param(TRelation* rel, const TString& j, int to);
   void parse_join();
@@ -1267,6 +1278,15 @@ const TString& TCursor_parser::pop()
   return _token;
 }
 
+const TString& TCursor_parser::line()
+{
+  if (_pushed.not_empty())
+    return pop();
+  char* buff = _token.get_buffer(256);
+  _instr.getline(buff, _token.size());
+  return _token;
+}
+
 void TCursor_parser::push()
 {
   CHECK(_pushed.empty(), "Repushing?");
@@ -1299,6 +1319,26 @@ void TCursor_parser::parse_sortexpr(TToken_string& se)
   se.strip_d_spaces();
   se.replace(' ', sep);
   se.separator(sep);
+
+  // Trasforma i nomi dei files in numeri se necessario
+  if (se.find('.') > 0)
+  {
+    TToken_string fld(16, '.');
+    TString16 name;
+    for (int i = 0; se.get(i, fld); i++)
+    {
+      if (!isdigit(fld[0]) && fld.find('.') > 0)
+      {
+        fld.get(0, name);
+        const int num = ::table2logic(name);
+        if (num != 0)
+        {
+          fld.add(num, 0);
+          se.add(fld, i);
+        }
+      }
+    }
+  }
 }
 
 void TCursor_parser::parse_filter(TToken_string& filter)
@@ -1312,10 +1352,17 @@ void TCursor_parser::parse_filter(TToken_string& filter)
   push();
 }
 
+void TCursor_parser::parse_select(TToken_string& filter)
+{
+  filter = line();
+  filter.trim();
+}
+
+
 void TCursor_parser::parse_region(TRectype& rec)
 {
   TString16 field;
-  TString value;
+  TString80 value;
   while (true)
   {
     const TString& ass = pop();
@@ -1416,7 +1463,7 @@ void TCursor_parser::parse_sortedjoin()
   pop();
   if (tok.starts_with("FI") || tok.starts_with("SE")) 
   {
-    parse_filter(filter);
+    parse_select(filter);
   } 
   else 
     push();
@@ -1526,7 +1573,7 @@ TCursor_parser::TCursor_parser(istream& instr, TArray& col)
 	TToken_string filter;
 
 	if (tok.starts_with("FI") || tok.starts_with("SE"))
-    parse_filter(filter);
+    parse_select(filter);
   else
     push();
 
diff --git a/include/report.cpp b/include/report.cpp
index 3b214209e..4f9fcb586 100755
--- a/include/report.cpp
+++ b/include/report.cpp
@@ -1102,9 +1102,8 @@ const TRectangle& TReport_field::get_draw_rect() const
   TRectangle& rct = ((TReport_field*)this)->_draw_rct;
   if (dynamic_height())
   {
-    TParagraph_string str(formatted_text(), rct.width()/100);
-    str.rtrim();
-    int h = str.items() * 110; h -= h%100; // Sto un po' abbondante
+    TParagraph_string str(formatted_text(), rct.width()/100-1);  // Sto un po' scarso
+    int h = str.items() * 100;
     if (h <= 0)
       h = 100;
     if (h > _rct.height())
@@ -1418,11 +1417,13 @@ const TString& TReport_field::formatted_text() const
         tmp << _picture << ' ' << _var.as_string();
       return tmp;
     }
-    if (dynamic_height() && _var.as_string().find(char(0xB6)) >= 0)
+    if (dynamic_height())
     {
       TString& tmp = get_tmp_string();
       tmp = _var.as_string();
+      tmp.strip_d_spaces();
       tmp.replace(char(0xB6), '\n');
+      tmp.rtrim();
       return tmp;
     }
     return _var.as_string();
@@ -2206,22 +2207,23 @@ bool TReport::execute_prescript()
     bool bAsk = true;
     
     // Script dei poveri: lancia la maschera associata al report
-    if (use_mask())
+     if (use_mask())
 		{
-			TFilename msk = _path.name(); msk.ext("msk");
-			if (msk.custom_path())
-			{
-				TFilename ini = msk; ini.ext("ini");
-				// Attenzione: se esiste il .ini allora e' una maschera delle vendite!
-				if (!ini.exist()) 
-				{
-					bAsk = false;  // Non richiedere variabili
-					const KEY key = run_form(msk.name());
-					ok = key != K_ESC && key != K_QUIT;
-				}
-			}
-		}
-    
+      TFilename msk = _path.name(); msk.ext("msk");
+      if (msk.custom_path())
+      {
+        TFilename ini = msk; ini.ext("ini");
+        // Attenzione: se esiste il .ini allora e' una maschera delle vendite!
+        if (!ini.exist()) 
+        {
+          bAsk = false;  // Non richiedere variabili
+          const KEY key = run_form(msk.name());
+          ok = key != K_ESC && key != K_QUIT;
+        }
+      }
+    }
+
+
     if (bAsk)
     {
       // Script dei poverissimi: chiede le eventuali variabili
@@ -2537,6 +2539,17 @@ void TReport::mask2report(const TMask & m)
   }
 }
 
+KEY TReport::run_form(TMask& m)
+{
+  report2mask(m);
+  KEY key = m.run();
+  if (key != K_QUIT && key != K_ESC)
+		mask2report(m);      // Rendi visibili tutte le variabili utente al report
+   
+  return key;
+}
+
+
 KEY TReport::run_form(const TString& maskname)
 {
   TFilename fname = maskname; fname.ext("msk");
@@ -2544,12 +2557,9 @@ KEY TReport::run_form(const TString& maskname)
   if (fname.custom_path())
   {
     TMask m(maskname);
-
-		report2mask(m);
-    key = m.run();
-    if (key != K_QUIT && key != K_ESC)
-			mask2report(m);      // Rendi visibili tutte le variabili utente al report
+    key = run_form(m);
   }
+
   return key;
 }
 
@@ -2950,4 +2960,3 @@ TReport::~TReport()
 { 
   destroy();
 }
-
diff --git a/include/report.h b/include/report.h
index 763f6e1ad..8df65cc72 100755
--- a/include/report.h
+++ b/include/report.h
@@ -455,7 +455,9 @@ protected:
   virtual bool execute_usr_word(unsigned int opcode, TVariant_stack& stack);
   virtual bool get_usr_val(const TString& name, TVariant& var) const;
   virtual bool set_usr_val(const TString& name, const TVariant& var);
-  KEY run_form(const TString& msk);
+
+  virtual KEY run_form(TMask& msk);
+  virtual KEY run_form(const TString& msk);
   
   bool do_message(const TVariant& var, FLDMSG_FUNC msg, void* jolly);
 
@@ -528,19 +530,22 @@ public:
 
   // Used by TReport_printer
   void set_page(word r, word p) { _rep_page = r; _book_page = p; } 
-
+	word page() const { return _rep_page; }
+	virtual word last_printed_page() const { return 0; }
+	
   void set_curr_field(TReport_field* fld) { _curr_field = fld; }
   TReport_field* curr_field() const { return _curr_field; }
 
   int parse_field(const char* code, char& type, int& level, int& id) const;
   TReport_field* field(const char* code);
 
-	void report2mask(TMask & m) const;
-	void mask2report(const TMask & m);
-  
-	void destroy();
+  void report2mask(TMask & m) const;
+  void mask2report(const TMask & m);
+
+  void destroy();
+
   TReport();
   virtual ~TReport();
 };
 
-#endif
+#endif
\ No newline at end of file
diff --git a/include/reprint.cpp b/include/reprint.cpp
index 1344241fd..5e24a17c8 100755
--- a/include/reprint.cpp
+++ b/include/reprint.cpp
@@ -1337,7 +1337,7 @@ bool TBook::init()
   bool ok = true;
   if (_pvr < 96 || _phr < 96) // Risoluzione di Acrobat Writer
   {
-    ok = yesno_box(TR("Stampante obsoleta o non adeguatamente configurata:\n"
+    ok = yesno_box(FR("Stampante obsoleta o non adeguatamente configurata:\n"
                       "Risoluzione %ldx%ld. Continuare ugualmente?"), _phr, _pvr);
   }
   return ok;
@@ -1751,7 +1751,7 @@ bool TReport_book::add(TReport& rep, bool progind)
   const int max_body = _report->find_max_level('B');
   int last_body_height = 0;
   
-  _rep_page = 0; // Azzera numero di pagina relativo
+  _rep_page = rep.last_printed_page(); // Azzera numero di pagina relativo
   _is_last_page = false;
 	
 	bool ok = rex->move_to(0);
diff --git a/include/sheet.cpp b/include/sheet.cpp
index 62288e9a0..d3f712b91 100755
--- a/include/sheet.cpp
+++ b/include/sheet.cpp
@@ -800,10 +800,7 @@ bool TSheet_control::event_handler(XI_OBJ* itf, XI_EVENT *xiev)
             xiev->v.cell_request.back_color = FOCUS_BACK_COLOR; 
           }
           else
-          {
-            xiev->v.cell_request.color = 0; 
-            xiev->v.cell_request.back_color = 0; 
-          }
+            _sheet->get_cell_colors(rec, col, xiev->v.cell_request.color, xiev->v.cell_request.back_color); 
       }  
     } 
     else
@@ -1045,6 +1042,12 @@ void TSheet::add_button(
   butt.set_exit_key(key);
 }
 
+bool TSheet::get_cell_colors(int row, int col, COLOR& fore, COLOR& back) const 
+{ 
+  fore = back = 0;   // Default colors
+  return false;      // Not assigned
+}  
+
 void TSheet::repos_buttons() const
 {      
   if (_sheet == NULL)
@@ -1337,6 +1340,27 @@ long TArray_sheet::insert(const TToken_string& s, long n)
 // TCursor_sheet
 ///////////////////////////////////////////////////////////
 
+bool TCursor_sheet::in_key(const TFieldref& fr) const
+{
+  const int logic = _cursor->file().num();
+  if (fr.file() != 0 && fr.file() != logic)
+    return false;
+
+  const RecDes& rd = prefix().get_recdes(logic);
+
+  const int key = _cursor->key();
+  const KeyDes& kd = rd.Ky[key-1];
+
+  for (int i = 0; i < kd.NkFields; i++)
+  {
+    const int n = kd.FieldSeq[i] % MaxFields;
+    if (strcmp(rd.Fd[n].Name, fr.name()) == 0)
+      return true;
+  }
+
+  return false;
+}
+
 TCursor_sheet::TCursor_sheet(TCursor* cursor, const char* fields,
                              const char* title, const char* head, 
                              byte buttons, short sht_y, WINDOW parent)
@@ -1362,6 +1386,8 @@ TCursor_sheet::TCursor_sheet(TCursor* cursor, const char* fields,
         if (c == ' ') 
           sheet().align_column(campo, TRUE);
       }  
+
+      _key_cols.set(campo, in_key(fr));
     }
   }  
 }
@@ -1396,6 +1422,18 @@ void TCursor_sheet::get_row(long row, TToken_string& l)
   }
 }
 
+bool TCursor_sheet::get_cell_colors(int row, int col, COLOR& fore, COLOR& back) const
+{
+  if (_key_cols[col])
+  {
+    fore = 0;
+    back = REQUIRED_BACK_COLOR;
+    return true;
+  }
+  return TSheet::get_cell_colors(row, col, fore, back);
+}
+
+
 ///////////////////////////////////////////////////////////
 // TBrowse_sheet
 ///////////////////////////////////////////////////////////
diff --git a/include/sheet.h b/include/sheet.h
index 4246cca85..582cd8ce5 100755
--- a/include/sheet.h
+++ b/include/sheet.h
@@ -40,6 +40,7 @@ protected:
                                 
   // @cmember Permette di riposizionare i bottoni all'interno della pagina
   virtual void repos_buttons() const;
+  virtual bool get_cell_colors(int row, int col, COLOR& fore, COLOR& back) const;
   
   void post_select(long rec);
   
@@ -173,6 +174,8 @@ class TCursor_sheet : public TSheet
   // @cmember:(INTERNAL) Cursore da cui prelevare i dati
   TCursor* _cursor;
 
+  TBit_array _key_cols; // Colonne colorate;
+
   // @access Protected Member
 protected:  // TSheet
   
@@ -183,6 +186,9 @@ protected:  // TSheet
   // @cmember Ritorna la riga n
   virtual void get_row(long n, TToken_string& row);
 
+  bool in_key(const TFieldref& fr) const;
+  virtual bool get_cell_colors(int row, int col, COLOR& fore, COLOR& back) const;
+
   // @access Public Member
 public: // TSheet
   
diff --git a/mr/f152.dir b/mr/f152.dir
index 24c45f19a..7b2a1b39b 100755
--- a/mr/f152.dir
+++ b/mr/f152.dir
@@ -1,3 +1,3 @@
 152
 0
-$rilprod|1|1|116|0|Rilevazione produzione|||
+$rilprod|0|0|127|0|Rilevazione produzione|||
diff --git a/mr/f152.trr b/mr/f152.trr
index f3c32cda4..a43d6ce4d 100755
--- a/mr/f152.trr
+++ b/mr/f152.trr
@@ -1,7 +1,7 @@
 152
-20
+19
 CODART|1|20|0|Codice articolo
-DATAPROD|5|8|0|Data di inizio produzione
+DATA|5|8|0|Data di scadenza
 PROG|2|3|0|Progressivo del giorno
 CODNUM|1|4|0|Codice numerazione ordine di produzione
 ANNO|2|4|0|Anno ordine di produzione
@@ -9,11 +9,10 @@ PROVV|1|1|0|Tipo numerazione <P>rovvisorio <D>efinitivo ordine di produzione
 NDOC|3|7|0|Numero documento ordine di produzione
 IMPIANTO|1|5|0|Codice impianto
 LINEA|1|5|0|Codice linea
+OPERATORE|1|16|0|Codice Operatore
 NRIGA|2|3|0|Numero riga ordine di produzione
-ORAPROD|1|6|0|Ora di inizio produzione
-DATAFINE|5|8|0|Data fine produzione
-ORAFINE|1|6|0|Ora fine produzione
-QTA|4|15|5|Quantit� prodotta
+QTA|4|15|5|Quantit� prodotta totale
+SCARTO|4|15|4|Scarto di produzione totale
 CHIUSO|8|1|0|Lotto chiuso
 CODNUMP|1|4|0|Codice numerazione bolla di produzione
 ANNOP|2|4|0|Anno bolla di produzione
@@ -21,9 +20,9 @@ PROVVP|1|1|0|Tipo numerazione <P>rovvisorio <D>efinitivo bolla di produzione
 NDOCP|3|7|0|Numero documento bolla di produzione
 NRIGAP|2|3|0|Numero riga bolla di produzione
 6
-CODART+DATAPROD+PROG| 
-IMPIANTO+LINEA+CODART+DATAPROD|X
-DATAPROD+IMPIANTO+LINEA+CODART|X
+CODART+DATA+PROG| 
+IMPIANTO+LINEA+CODART+DATA|X
+DATA+IMPIANTO+LINEA+CODART|X
 PROVV+ANNO+CODNUM+NDOC+NRIGA|X
 PROVVP+ANNOP+CODNUMP+NDOCP+NRIGAP|X
-CODNUM+ANNO+PROVV+NDOC+CODART+DATAPROD|X
+CODNUM+ANNO+PROVV+NDOC+CODART+DATA|X
diff --git a/mr/f153.dir b/mr/f153.dir
new file mode 100755
index 000000000..e9042c87a
--- /dev/null
+++ b/mr/f153.dir
@@ -0,0 +1,3 @@
+153
+0
+$rrilprod|0|0|93|0|Righe rilevazione produzione|||
diff --git a/mr/f153.trr b/mr/f153.trr
new file mode 100755
index 000000000..7aaedaacb
--- /dev/null
+++ b/mr/f153.trr
@@ -0,0 +1,14 @@
+153
+10
+CODART|1|20|0|Codice articolo
+DATA|5|8|0|Data consegna
+PROG|2|3|0|Progressivo
+NRIGA|2|3|0|Numero di riga
+DATAINI|5|8|0|Data inizio produzione
+ORAINI|1|6|0|Ora di inizio produzione
+DATAFINE|5|8|0|Data fine produzione
+ORAFINE|1|6|0|Ora fine produzione
+QTA|4|15|5|Quantit� prodotta
+SCARTO|4|15|4|Scarto di produzione
+1
+CODART+DATA+PROG+NRIGA| 
diff --git a/mr/mr0500.cpp b/mr/mr0500.cpp
index b4b69b3c1..11f52c49c 100755
--- a/mr/mr0500.cpp
+++ b/mr/mr0500.cpp
@@ -1,12 +1,100 @@
 #include <automask.h>
+#include <defmask.h>
+#include <filetext.h>
+#include <printer.h>
+#include <progind.h>
 #include <relapp.h>
+#include <modaut.h>
 #include <utility.h>
+#include <viswin.h>
 
+#include "../ve/velib.h"
 #include "mr0500a.h"
+#include "mr0500b.h"
+#include "mr0500c.h"
+#include "mrplib.h"
+
+///////////////////////////////////////////////////////////
+// TElabora_mask
+///////////////////////////////////////////////////////////
+class TElabora_mask : public TAutomask
+{ 
+
+protected:
+  virtual bool on_field_event(TOperable_field& o, TField_event e, long jolly);
+
+public:
+  TElabora_mask() : TAutomask("mr0500c") { }
+};
+
+bool TElabora_mask::on_field_event(TOperable_field& o, TField_event e, long jolly)
+{
+	return true;
+}
+
+///////////////////////////////////////////////////////////
+// TLoadfile_mask
+///////////////////////////////////////////////////////////
+class TLoadfile_mask : public TAutomask
+{ 
+
+protected:
+  virtual bool on_field_event(TOperable_field& o, TField_event e, long jolly);
+
+public:
+  TLoadfile_mask() : TAutomask("mr0500b") { }
+};
+
+bool TLoadfile_mask::on_field_event(TOperable_field& o, TField_event e, long jolly)
+{
+  switch (o.dlg())                                                                      //eventi, tipo pressione dei tasti
+  {       
+  case F_FILE:
+    if(e==fe_button)                   //se e (che � l'evento) = pressione del bottone 'cerca' (fe button)
+    {
+      DIRECTORY dir; 
+      FILE_SPEC fs;
+    
+      TFilename fname=o.get();         //se il nome del file non esiste -> gli assegna automaticamente il nome
+      if(fname == "")                  //articoli.dat
+        fname = "articoli";
+      
+      xvt_fsys_get_dir(&dir);          //funzioni di xvt (grafica); utilizzate per creare la finestra di ricerca del
+      xvt_fsys_get_dir(&fs.dir);       //file di tipo .dat (� una finestra tipo gestione risorse Windows)
+      strcpy(fs.type, "dat");
+      strcpy(fs.name, fname);
+      strcpy(fs.creator, "ELD");
+        
+      const bool good = xvt_dm_post_file_open(&fs, "Selezionare il file ...") == FL_OK;
+      xvt_fsys_set_dir(&dir);
+                     
+      if (good)
+      {                 
+        xvt_fsys_convert_dir_to_str(&fs.dir, fname.get_buffer(), fname.size());   //converte il nome della directory in una
+        fname.add(fs.name);                                                       //stringa aggiungendo il path del file
+        o.set(fname);                                                         //mostra il campo sul video (la funzione set) 
+      }
+      
+    }
+    if(e==fe_init && o.get().empty())                  
+			o.set("prod.dat");
+    if(e==fe_close)                //se e = alla pressione del bottone 'chiudi' (fe_close) controlla che il campo sia stato
+    {                              //riempito correttamente nella maschera
+      TFilename n = o.get();
+      return n.exist();
+    }     
+    break;
+		default:
+    break;
+	}
+	return true;
+}
 
 ///////////////////////////////////////////////////////////
 // TRilprod_mask
 ///////////////////////////////////////////////////////////
+typedef enum TTipo_rec { _no_type = 0, _start = 1, _end = 2, _rett = 3};
+
 class TRilprod_mask : public TAutomask
 { 
 
@@ -15,12 +103,23 @@ protected:
   virtual bool on_key(KEY key);
 
 public:
-  TRilprod_mask() : TAutomask("mr0500a") { }
+  void load_prod_file(const char * nomefile, bool savefile, bool only_errors);
+	void display_error(TViswin & v, const char * msg, TTracciato_record & t, TRecord_text & r);
+	void print_record(TViswin & v, TTipo_rec t , TProduzione & r);
+  TRilprod_mask();
+	virtual ~TRilprod_mask() {}
+
 };
 
+TRilprod_mask::TRilprod_mask() : TAutomask("mr0500a")
+{
+	enable(F_DATALOG, main_app().has_module(POAUT, CHK_DONGLE));
+	sfield(F_TEMPI).set_append(false);
+}
+
 bool TRilprod_mask::on_key(KEY key)
 {
-  //shift+f12 per abilitare il riquadro della bolla di protezione
+  //shift+f12 per abilitare il riquadro della bolla di produzione
   if (key == K_SHIFT + K_F12)
   {
     enable(-GR_BOLPROD);
@@ -34,34 +133,505 @@ bool TRilprod_mask::on_field_event(TOperable_field& o, TField_event e, long joll
   bool ok = true;
   switch (o.dlg())
   {
-  case F_ORAINI :
-  case F_MININI :
-  case F_SECINI :
-  case F_ORAFIN :
-  case F_MINFIN :
-  case F_SECFIN :
+  case F_TEMPI:
+		if (e == se_notify_add || e == se_notify_del)
+		{
+			TSheet_field & sh = (TSheet_field &)o;
+			TMask_field & q = field(F_QTA);
+			TMask_field & s = field(F_SCARTO);
+			const int items = sh.items();
+			const bool enable = items == 0;
+			
+			if (enable)
+			{
+				q.enable(); q.reset();
+				s.enable(); s.reset();
+			}
+			else
+			{
+				q.disable();
+				s.disable();
+			}
+		}
+		else
+			if (e == se_leave)
+			{
+				TSheet_field & sh = (TSheet_field &)o;
+				TMask_field & q = field(F_QTA);
+				TMask_field & s = field(F_SCARTO);
+				const int items = sh.items();
+				if (items > 0)
+				{
+					real qta;
+					real scarto;
+
+					for (int i = 0; i < items; i++)
+					{
+						TToken_string & r = sh.row(i);
+						
+						qta += (real)r.get(sh.cid2index(FR_QTA));
+						scarto += (real)r.get(sh.cid2index(FR_SCARTO));
+					}
+					q.set(qta.string());
+					s.set(scarto.string());
+				}
+			}
+		break;
+  case FR_ORAINI :
+  case FR_MININI :
+  case FR_SECINI :
+  case FR_ORAFIN :
+  case FR_MINFIN :
+  case FR_SECFIN :
     if (e == fe_modify || e == fe_close)
     {
       //i campi ore/min/sec vanno zero filled
       TString8 stringa;
-      int numero = atoi(o.get());
-      stringa.format("%02d", numero);
-      o.set(stringa);
-    }
-    break;
-  case F_DATAFIN :
-    if (e == fe_close)
-    {
-      if (o.get().not_empty() && get_real(F_QTA) <= 0.0)
-        return error_box(FR("La quantita' deve essere >0 avendo\n indicato una data di fine produzione"));
+			if (o.get().not_empty())
+			{
+	      int numero = atoi(o.get());
+		    stringa.format("%02d", numero);
+				o.set(stringa);
+			}
     }
     break;
+  case H_PROG :
+		if (e == fe_modify && key_valid(1))
+			stop_run(K_AUTO_ENTER);
+		break;
+  case DLG_ELABORA :
+    if (e == fe_button)
+		{
+			TElabora_mask m;
+
+			if (m.run() == K_ENTER)
+			{
+				TConsuntivazione_produzione c(m.get(F_CODICE_EL));
+				TLista_documenti docs;
+				TDate d(m.get(F_DATA_EL));
+
+				if (c.elabora(docs, docs, d, true))
+					docs[0].rewrite();
+			}
+		}
+		break;
+  case F_DATALOG :
+    if (e == fe_button)
+		{
+			TLoadfile_mask m;
+
+			if (m.run() == K_ENTER)
+				load_prod_file(m.get(F_FILE), m.get_bool(F_SAVE), m.get_bool(F_ONLY_ERRORS));
+		}
   default: 
     break;
   }
   return ok;
 }
 
+void TRilprod_mask::display_error(TViswin & v, const char * msg, TTracciato_record & t, TRecord_text & r)
+{
+  TString riga;
+	const int nfields = t.tracciati_campo().items();
+
+  v.add_line("");
+	v.add_line(format(FR("Errore : %s"), msg));
+	TString l;
+	for (int f = 0; f < nfields; f++)
+	{
+		const TTracciato_campo & c = t.get(f);
+		const TString & name = c.name();
+		TString  val(r.get(f));
+		TString s;
+		
+		val.trim();
+		s.format(" %s = %s", (const char *) name,  (const char *) val);
+
+		if (l.len() + s.len() > 80)
+		{
+			v.add_line(l);
+			l.cut(0);
+		}
+		l << s;
+	}
+	if (l.not_empty())
+		v.add_line(l);
+}
+
+void TRilprod_mask::print_record(TViswin & v, TTipo_rec t , TProduzione & r)
+{
+  TString riga;
+	const int nfields = r.rec_des()->NFields;
+
+  v.add_line("");
+	if (t == _start)
+		v.add_line(TR("Record elaborato - inizio produzione"));
+	else
+		if (t == _end)
+			v.add_line(TR("Record elaborato - fine produzione"));
+		else
+			if (t == _rett)
+				v.add_line(TR("Record elaborato - rettifica"));
+	TString l;
+	for (int i = 0; i < nfields; i++)
+	{
+		const TString & name = r.fieldname(i);
+		const TString & val = r.get(name);
+
+		TString s;
+		
+		s.format(" %s = %s", (const char *) name,  (const char *) val);
+
+		if (l.len() + s.len() > 80)
+		{
+			v.add_line(l);
+			l.cut(0);
+		}
+		l << s;
+	}
+	if (l.not_empty())
+		v.add_line(l);
+}
+
+void TRilprod_mask::load_prod_file(const char * nomefile, bool savefile, bool only_errors)
+{                
+  TViswin vwin(NULL, TR("Importazione produzione"), FALSE, TRUE, TRUE);
+  TFile_text prod(nomefile,"mr0500a.ini");         //crea un oggetto articoli di tipo TFile_text
+  TRecord_text rec;                             //crea un record vuoto con nome articolocor 
+	TTracciato_record & trec = *(prod.t_rec(""));
+	const int nfields = trec.tracciati_campo().items();
+	int type_field = 0;
+	int ord_field = 0;
+	int cod_field = 0;
+	TDate filedate;
+  TProduzione prd;
+  TLocalisamfile rigaord(LF_RIGHEDOC);
+	TString val;
+	TString codart;
+	TLocalisamfile fp(LF_RILPROD);
+	TRectype cmp(fp.curr());
+	const long max = fsize(nomefile);
+	
+	TProgind p(max, format(FR("Importazione produzione : file %s"), nomefile));
+
+	for (int f = 0; f < nfields; f++)
+	{
+		const TTracciato_campo & c = trec.get(f);
+		const TString name = c.name();
+
+		if (name == "TIPO")
+			type_field = f;
+		else
+			if (name == "ORDINE")
+				ord_field = f;
+			else
+				if (name == "CODART")
+					cod_field = f;
+  }                                                       
+  vwin.open_modal();
+  prod.open();                  //applico il metodo open che apre il file in lettura (contenuta in TFile_text)
+	while(prod.ok_r())             //ok_r � una funzione che indica la fine del file
+  { 
+    if(prod.read(rec) == NOERR)
+    {
+			const TTipo_rec tipo = (TTipo_rec) atoi(rec.get(type_field));
+
+			p.setstatus(prod.read_file()->tellg());
+			if (tipo == _no_type)
+			{
+				display_error(vwin, TR("Tipo record non valido - record scartato"), trec, rec);
+				continue;
+			}
+
+			const TString ordval(rec.get(ord_field));
+
+			if (ordval.blank())
+			{
+				display_error(vwin, TR("Record vuoto - record scartato"), trec, rec);
+				continue;
+			}
+			if (ordval.find('.') < 0)
+			{
+				display_error(vwin, TR("Riga ordine errata - record scartato"), trec, rec);
+				continue;
+			}
+
+			TToken_string ord(ordval, '.');	ord.trim();
+			const TString codnum(ord.get(0));
+			const int anno = ord.get_int();
+			const int ndoc = ord.get_long();
+			const int nriga = ord.get_int();
+			TDate d;
+			TString h;
+			real qta;
+			real scarto;
+
+
+			rigaord.zero();
+			rigaord.put("CODNUM", codnum);
+			rigaord.put("ANNO", anno);
+			rigaord.put("PROVV", "D");
+			rigaord.put("NDOC", ndoc);
+			rigaord.put("NRIGA", nriga);
+
+			codart.cut(0);
+			TDate datao(TODAY);
+
+			if (rigaord.read(_isequal) != NOERR)
+				display_error(vwin, TR("Riga ordine inesistente"), trec, rec);
+			else
+			{
+				codart = rigaord.get("CODART");
+				TToken_string key;
+				key.add("D");
+				key.add(anno);
+				key.add(codnum);
+				key.add(ndoc);
+
+				const TRectype  & doc = cache().get(LF_DOC, key);
+				datao = doc.get_date("DATADOC");
+			}
+			TString codart_new(rec.get(cod_field));	codart_new.trim();
+			const int err = prd.read_ordp(codnum, anno, 'D', ndoc, nriga);
+			TDate datarec;
+			bool nuovo = (err != NOERR);
+			if (!nuovo)
+			{
+				fp.setkey(4);
+				cmp.zero();
+				cmp.put("CODNUM", codnum);
+				cmp.put("ANNO", anno);
+				cmp.put("PROVV", "D");
+				cmp.put("NDOC", ndoc);
+				cmp.put("NRIGA", nriga);
+				fp.curr() = cmp;
+				if (codart_new.not_empty())
+				{
+					nuovo = true;
+					for (int err = fp.read(); (err == NOERR) && (fp.curr() == cmp);	err = fp.next())
+					{
+						if (codart_new == fp.get("CODART"))
+						{
+							nuovo = false;
+							datarec = fp.get_date("DATA");
+							break;
+						}
+					}
+				}
+				else
+				{
+					TRecnotype r = -1L;
+					for (int err = fp.read(); (err == NOERR) && (fp.curr() == cmp);	err = fp.next())
+					{
+						const TRecnotype pos = fp.recno();
+						if (r < pos)
+							r = pos;
+					}
+					if (r >= 0L)
+					{
+						fp.readat(r);
+						codart_new = fp.curr().get("CODART");
+						datarec = fp.get_date("DATA");
+					}
+				}
+			}
+			if (codart_new.empty())
+			{
+				display_error(vwin, TR("Articolo nullo - record scartato"), trec, rec);
+				continue;
+			}
+			else
+			{
+				const TRectype & anamag = cache().get(LF_ANAMAG, codart_new);
+
+				if (anamag.empty())
+				{
+					display_error(vwin, TR("Articolo inesistente - record scartato"), trec, rec);
+					continue;
+				}
+			}
+
+
+
+			if (nuovo)
+			{
+				prd.zero();
+				prd.put("CODNUM", codnum);
+				prd.put("ANNO", anno);
+				prd.put("PROVV", "D");
+				prd.put("NDOC", ndoc);
+				prd.put("NRIGA", nriga);
+				prd.put("DATA", datao);
+			}
+			else
+				prd.read_art(codart_new, datarec, 0);
+
+			for (int f = 0; f < nfields; f++)
+			{
+				const TTracciato_campo & c = trec.get(f);
+				const TString name = c.name();
+				
+				val = rec.get(f);
+				val.trim();
+
+				if (!val.empty() || tipo == _rett)
+				{
+					if (name == "TIPO" || name == "ORDINE")
+						continue;
+					else
+						if (name == "DATA")
+						{ 
+							if (val.len() == 8)
+								val.insert("20", 6);
+							d = val;
+						}
+						else
+							if (name == "ORA")
+							{ 
+								h = val.left(2);
+								h << val.mid(3, 2) << val.right(2);
+							}
+							else
+								if (name == "QTA")
+									qta = (real) val;
+								else
+									if (name == "SCARTO")
+										scarto = (real) val;
+									else
+										prd.put(name, val);
+				}
+
+      }
+			if (prd.get("IMPIANTO").empty())
+			{
+				const TString16 linea(prd.get("LINEA"));
+				if (linea.not_empty())
+				{
+					const TLinea_prod lp(linea);
+					const TString16  imp(lp.codimp());
+					if (imp.not_empty())
+						prd.put("IMPIANTO", imp);
+				}
+			}
+			if (!only_errors)
+				print_record(vwin, tipo, prd);
+			if (tipo == _start)
+			{
+				const int rows = prd.body().rows();
+				bool found = false;
+				bool seq_err = false;
+
+				for (int i = 1; !found && i <= rows; i++)
+				{
+					const TRectype & row = prd.body()[i];
+					found = d == row.get_date("DATAINI") && h == row.get("ORAINI");
+					if (row.get("DATAFINE").empty())
+						seq_err = true;
+				}
+				if (seq_err)
+        		display_error(vwin, TR("Inizio senza fine precedente"), trec, rec);
+				if (!found)
+				{
+					TRectype & row = prd.body().row(rows + 1, true);
+					row.put("DATAINI", d);
+					row.put("ORAINI", h);
+				}
+				if (nuovo)
+					prd.write();
+				else
+					prd.rewrite();
+			}
+			else
+				if (tipo == _end)
+				{
+					const int rows = prd.body().rows();
+					bool found = false;
+
+					for (int i = rows; i > 0; i--)
+					{
+						const TRectype & row = prd.body()[i];
+						found = (d == row.get_date("DATAFINE") && h == row.get("ORAFINE")) ||
+										row.get("DATAFINE").empty();
+						if (found)
+							break;
+					}
+					if (!found)
+					{
+						TRectype & row = prd.body().row(rows + 1, true);
+						i = rows + 1;
+        		display_error(vwin, TR("Fine senza inizio"), trec, rec);
+					}
+					TRectype & row = prd.body()[i];
+
+					row.put("DATAFINE", d);
+					row.put("ORAFINE", h);
+					
+					real diff = qta - row.get_real("QTA");
+					real tot = prd.get_real("QTA") + diff;
+					
+					row.put("QTA", qta);
+					prd.put("QTA", tot);
+					diff = scarto - row.get_real("SCARTO");
+					tot = prd.get_real("SCARTO") + diff;
+					row.put("SCARTO", scarto);
+					prd.put("SCARTO", tot);
+					prd.rewrite();
+				}
+				else
+				{
+					const int rows = prd.body().rows();
+
+					for (int i = 1; i <= rows; i++)
+					{
+						TRectype & row = prd.body()[i];
+						if (i < rows)
+						{
+							row.zero("QTA");
+							row.zero("SCARTO");
+						}
+						else
+						{
+							row.put("QTA", qta);
+							row.put("SCARTO", scarto);
+						}
+					}
+					prd.put("QTA", qta);
+					prd.put("SCARTO", scarto);
+					prd.rewrite();
+				}
+    }                                             
+  }
+	prod.close();
+	if (savefile)
+	{
+		TFilename dest(nomefile);
+		dest = dest.path();
+		TString filemask(dest);
+		TString_array arr;
+		int cnt = 0;
+
+		filemask << "pr" << filedate.month() << filedate.day() << "*.dat";
+		list_files(filemask, arr);
+
+		const int items = arr.items();
+		if (items > 0)
+		{
+			arr.sort();
+			cnt = atoi(arr.row(items - 1).right(5));
+		}
+		cnt++;
+		dest << "pr" << filedate.month() << filedate.day() << cnt; dest.ext("dat");
+		if (fcopy(nomefile, dest))
+			remove_file(nomefile);
+
+	}
+  vwin.close_print();
+  vwin.close_modal();  
+  KEY k = vwin.run();
+  if (k == K_CTRL+'S') // Ho premuto Stampa
+    printer().print_txt(vwin.text());
+}
+
 ///////////////////////////////////////////////////////////
 // TRilprod_app
 ///////////////////////////////////////////////////////////
@@ -71,6 +641,11 @@ class TRilprod_app : public TRelation_application
   TRelation* _rel;
   TRilprod_mask* _msk;
 
+  virtual int read( TMask& m );
+  virtual int write( const TMask& m );
+  virtual int rewrite( const TMask& m );
+  virtual bool remove();
+
 protected:
   virtual TMask* get_mask(int) { return _msk; }
   virtual TRelation* get_relation() const { return _rel; }
@@ -85,6 +660,8 @@ protected:
 void TRilprod_app::init_insert_mode(TMask& m)
 {                
   m.disable(-GR_BOLPROD);
+	m.field(F_QTA).enable();
+	m.field(F_SCARTO).enable();
 }
 
 void TRilprod_app::init_modify_mode(TMask& m)
@@ -112,28 +689,173 @@ bool TRilprod_app::get_next_key(TToken_string& key)
 {
   TMask& m = curr_mask( );
   
-  if (m.get(F_CODART).empty() || m.get(F_DATAPROD).empty())
+  if (m.get(F_CODART).empty() || m.get(F_DATA).empty())
     return false;
 
-  TLocalisamfile rilprod(LF_RILPROD);
-  rilprod.put("CODART", m.get(F_CODART));
-  rilprod.put("DATAPROD", m.get(F_DATAPROD));
+  TProduzione p;
+	
+  int n = 0;
+  
+  TLocalisamfile ril(LF_RILPROD);
+  TRectype& curr = ril.curr();
+	
+	curr.put("CODART", m.get(F_CODART));
+	curr.put("DATA", m.get_date(F_DATA));
+  curr.put("PROG", 999);
 
-  TRectype cmp_rec(rilprod.curr());   // record campione
-
-  rilprod.put( "PROG", 999 );
-  if (rilprod.read(_isgreat) == NOERR)
-    rilprod.prev();
-  else
-    rilprod.last();
-
-  const int num = ((rilprod.curr() == cmp_rec) ? rilprod.get_int("PROG") : 0) + 1;
-
-  key.format("%d|%d", F_PROG, num);
+  const int err = ril.read(_isgreat);
+              
+  if (err != _isemptyfile)
+  {
+    if (err == NOERR)
+      ril.prev();
+    if (curr.get("CODART") == m.get(F_CODART) && 
+        curr.get("DATA") == m.get_date(F_DATA))
+       n = curr.get_int("PROG");
+  }     
+  
+  n++;
 
+  key.format("%d|%d", F_PROG, n);
   return true;
 }
 
+int TRilprod_app::read( TMask& m )
+{
+	TProduzione p;
+  int err = TRelation_application::read(m);
+	
+	if (err != NOERR)
+		return err;
+	p.TMultiple_rectype::read(_rel->curr());
+
+	const int rows = p.body().rows();
+	TSheet_field & sh = m.sfield(F_TEMPI);
+
+	sh.reset();
+	for (int i = 0 ; i < rows; i++)
+	{
+		TToken_string & r = sh.row(i);
+		const TRectype & row = p.body()[i + 1];
+		r.add(row.get("DATAINI"));
+		const TString & oraini = row.get("ORAINI");
+		r.add(oraini.left(2));
+		r.add(oraini.mid(2, 2));
+		r.add(oraini.right(2));
+		r.add(row.get("DATAFINE"));
+		const TString & orafin = row.get("ORAFINE");
+		r.add(orafin.left(2));
+		r.add(orafin.mid(2, 2));
+		r.add(orafin.right(2));
+		r.add(row.get("QTA"));
+		r.add(row.get("SCARTO"));
+	}
+
+	const bool on = m.sfield(F_TEMPI).items() == 0;
+
+	m.field(F_QTA).enable(on);
+	m.field(F_SCARTO).enable(on);
+  return NOERR;
+}
+
+int TRilprod_app::write( const TMask& m )
+{   
+	TProduzione p;
+	TSheet_field & sh = m.sfield(F_TEMPI);
+	const int rows = sh.items();
+
+	p.zero();
+	m.autosave(*_rel);
+	p.head() = _rel->curr();
+	for (int i = 0 ; i < rows; i++)
+	{
+		TToken_string & r = sh.row(i);
+		TRectype & row = p.body().row(i + 1, true);
+		
+		row.put("DATAINI", r.get(0));
+		TString8 ora(r.get());
+		TString8 w(r.get());
+		if (w.blank())
+			w = "00"; 
+		ora << w;
+		w = r.get();
+		if (w.blank())
+			w = "00"; 
+		ora << w;
+		row.put("ORAINI", ora);
+		row.put("DATAFINE", r.get());
+		ora = r.get();
+		w = r.get();
+		if (w.blank())
+			w = "00"; 
+		ora << w;
+		w = r.get();
+		if (w.blank())
+			w = "00"; 
+		ora << w;
+		row.put("ORAFINE", ora);
+		row.put("QTA", r.get());
+		row.put("SCARTO", r.get());
+	}
+  const int err = p.write();
+	
+	_rel->curr() = p.head();
+	_rel->read();
+	return err;
+}
+
+int TRilprod_app::rewrite( const TMask& m )
+{
+	TProduzione p;
+	TSheet_field & sh = m.sfield(F_TEMPI);
+	const int rows = sh.items();
+
+	m.autosave(*_rel);
+	p.TMultiple_rectype::read(_rel->curr());
+	p.head() = _rel->curr();
+	p.destroy_rows();
+	for (int i = 0 ; i < rows; i++)
+	{
+		TToken_string & r = sh.row(i);
+		TRectype & row = p.body().row(i + 1, true);
+		
+		row.put("DATAINI", r.get(0));
+		TString16 ora(r.get());
+		TString8 w(r.get());
+		if (w.blank())
+			w = "00"; 
+		ora << w;
+		w = r.get();
+		if (w.blank())
+			w = "00"; 
+		ora << w;
+		row.put("ORAINI", ora);
+		row.put("DATAFINE", r.get());
+		ora = r.get();
+		w = r.get();
+		if (w.blank())
+			w = "00"; 
+		ora << w;
+		w = r.get();
+		if (w.blank())
+			w = "00"; 
+		ora << w;
+		row.put("ORAFINE", ora);
+		row.put("QTA", r.get());
+		row.put("SCARTO", r.get());
+	}
+  return p.rewrite();
+}
+
+bool TRilprod_app::remove()
+{
+	TProduzione p;
+
+	_msk->autosave(*_rel);
+	p.TMultiple_rectype::read(_rel->curr());
+  return p.remove() == NOERR;
+}
+
 int mr0500(int argc, char* argv[])
 {
   TRilprod_app app;
diff --git a/mr/mr0500a.h b/mr/mr0500a.h
index 36ed6a920..1e459affe 100755
--- a/mr/mr0500a.h
+++ b/mr/mr0500a.h
@@ -1,39 +1,47 @@
 //campi maschera mr0500a.uml
 
-#define F_CODART      101
-#define F_DATAPROD    102
-#define F_PROG        103
-#define F_IMPIANTO    104
-#define F_LINEA       105
-#define F_CODNUM      106
-#define F_ANNO        107
-#define F_PROVV       108
-#define F_NDOC        109
-#define F_NRIGA       110
+#define F_CODART      201
+#define F_DATA        202
+#define F_PROG        203
+#define F_IMPIANTO    204
+#define F_LINEA       205
+#define F_CODNUM      206
+#define F_ANNO        207
+#define F_PROVV       208
+#define F_NDOC        209
+#define F_NRIGA       210
 
-#define F_QTA         113
-#define F_CHIUSO      114
-#define F_CODNUMP     115
-#define F_ANNOP       116
-#define F_PROVVP      117
-#define F_NDOCP       118
-#define F_NRIGAP      119
+#define F_QTA         213
+#define F_CHIUSO      214
+#define F_CODNUMP     215
+#define F_ANNOP       216
+#define F_PROVVP      217
+#define F_NDOCP       218
+#define F_NRIGAP      219
 
-#define F_DESCRCOD    120
-#define F_DESCRIMP    121
-#define F_DESCRLIN    122
-#define F_DESCRNUM    123
-#define F_DESCRNUMP   124
+#define F_DESCRCOD    220
+#define F_DESCRIMP    221
+#define F_DESCRLIN    222
+#define F_DESCRNUM    223
+#define F_DESCRNUMP   224
+#define F_SCARTO    	225
 
-#define F_DATAINI     130
-#define F_ORAINI      131
-#define F_MININI      132
-#define F_SECINI      133
-#define F_DATAFIN     134
-#define F_ORAFIN      135
-#define F_MINFIN      136
-#define F_SECFIN      137
+#define F_BOTTONE     240
+#define F_DATALOG     241
+#define GR_BOLPROD    242
+#define F_OPERATORE   243
+#define F_COGNOME			244
+#define F_NOME	    	245
+#define F_TEMPI	    	246
+#define H_PROG        247
 
-#define F_BOTTONE     140
-#define F_DATALOG     141
-#define GR_BOLPROD    142
+#define FR_DATAINI    101
+#define FR_ORAINI     102
+#define FR_MININI     103
+#define FR_SECINI     104
+#define FR_DATAFIN    105
+#define FR_ORAFIN     106
+#define FR_MINFIN     107
+#define FR_SECFIN     108
+#define FR_QTA        109
+#define FR_SCARTO     110
diff --git a/mr/mr0500a.ini b/mr/mr0500a.ini
new file mode 100755
index 000000000..5077dbc63
--- /dev/null
+++ b/mr/mr0500a.ini
@@ -0,0 +1,31 @@
+[MAIN]
+DECSEP = 
+FIELDSEP = |
+RECORDSEP = 
+RECORDSIZE =
+SKIPLINES = 0
+TYPEFIELD = -1
+TYPELEN = 0
+TYPEPOS = -1
+
+[RECORD]
+LENGTH(0) = 1
+LENGTH(1) = 20
+LENGTH(2) = 20
+LENGTH(3) = 5
+LENGTH(4) = 8
+LENGTH(5) = 8
+LENGTH(6) = 15
+LENGTH(7) = 1
+LENGTH(8) = 5
+LENGTH(9) = 15
+NAME(0) = TIPO
+NAME(1) = ORDINE
+NAME(2) = CODART
+NAME(3) = LINEA
+NAME(4) = DATA
+NAME(5) = ORA
+NAME(6) = QTA
+NAME(7) = CHIUSO
+NAME(8) = OPERATORE
+NAME(9) = SCARTO
diff --git a/mr/mr0500a.uml b/mr/mr0500a.uml
index 82f04eee2..bdf7a915e 100755
--- a/mr/mr0500a.uml
+++ b/mr/mr0500a.uml
@@ -1,6 +1,22 @@
 #include "mr0500a.h"
 
-TOOLBAR "" 0 -2 0 2
+TOOLBAR "" 0 -4 0 4
+BUTTON 99 10 2
+BEGIN
+  PROMPT -13 -3 "~Aperti"
+	MESSAGE K_F9,H_PROG
+END
+
+BUTTON DLG_ELABORA 10 2
+BEGIN
+  PROMPT -23 -3 "E~labora"
+END
+
+BUTTON F_DATALOG 10 2
+BEGIN
+  PROMPT -33 -3 ""
+  PICTURE 20001
+END
 #include <toolbar.h>
 ENDPAGE
 
@@ -24,6 +40,7 @@ BEGIN
   FLAGS "U"
   KEY 1
   FIELD CODART
+  MESSAGE COPY,11@
 END
 
 STRING F_DESCRCOD 50
@@ -37,38 +54,70 @@ BEGIN
   COPY OUTPUT F_CODART  
   CHECKTYPE NORMAL
   KEY 1
+  MESSAGE COPY,12@
 END
 
-DATE F_DATAPROD
+DATE F_DATA
 BEGIN
-  PROMPT 2 3 "Data produzione "
+  PROMPT 2 3 "Data ordine     "
   CHECKTYPE REQUIRED
   KEY 1
-  FIELD DATAPROD
-  MESSAGE COPY,F_DATAINI
+  FIELD DATA
+  MESSAGE COPY,13@
 END
 
 NUMBER F_PROG 3
 BEGIN
   PROMPT 42 3 "Progressivo del giorno "
-  USE LF_RILPROD
+  USE LF_RILPROD KEY 6
+	JOIN LF_ANAMAG INTO CODART==CODART
   FLAGS "U"
-  INPUT CODART F_CODART SELECT
-  INPUT DATAPROD F_DATAPROD
-  INPUT PROG F_PROG
+  INPUT PROVV F_PROVV
+  INPUT ANNO F_ANNO
+  INPUT CODNUM F_CODNUM
+  INPUT NDOC F_NDOC
+  INPUT NRIGA F_NRIGA
+	DISPLAY "Ordine@10" NDOC
+	DISPLAY "Riga@7" NRIGA
   DISPLAY "Codice articolo@20" CODART
-  DISPLAY "Data prod." DATAPROD
+	DISPLAY "Descrizione@50" LF_ANAMAG->DESCR
+  DISPLAY "Data ordine" DATA
   DISPLAY "Prog." PROG
-  OUTPUT F_DATAPROD DATAPROD
+  OUTPUT F_CODART CODART 
+  OUTPUT F_DATA DATA
   OUTPUT F_PROG PROG
   CHECKTYPE REQUIRED
   KEY 1
   FIELD PROG
+  MESSAGE COPY,14@
+END
+
+NUMBER H_PROG 3
+BEGIN
+  PROMPT 42 3 ""
+  USE LF_RILPROD KEY 6 SELECT QTA==0
+	JOIN LF_ANAMAG INTO CODART==CODART
+  FLAGS "UHG"
+  INPUT PROVV F_PROVV
+  INPUT ANNO F_ANNO
+  INPUT CODNUM F_CODNUM
+  INPUT NDOC F_NDOC
+  INPUT NRIGA F_NRIGA
+	DISPLAY "Ordine@10" NDOC
+	DISPLAY "Riga@7" NRIGA
+  DISPLAY "Codice articolo@20" CODART
+	DISPLAY "Descrizione@50" LF_ANAMAG->DESCR
+  DISPLAY "Data ordine" DATA
+  DISPLAY "Prog." PROG
+  OUTPUT F_CODART CODART 
+  OUTPUT F_DATA DATA
+  OUTPUT F_PROG PROG
+  CHECKTYPE NORMAL
 END
 
 STRING F_IMPIANTO 5
 BEGIN
-  PROMPT 1 5 "Impianto "
+  PROMPT 1 5 "Impianto  "
   USE IMP
   INPUT CODTAB F_IMPIANTO
   DISPLAY "Codice" CODTAB
@@ -92,7 +141,7 @@ END
 
 STRING F_LINEA 5
 BEGIN
-  PROMPT 1 6 "Linea    "
+  PROMPT 1 6 "Linea     "
   USE LNP SELECT S6==#F_IMPIANTO
   INPUT CODTAB F_LINEA
   DISPLAY "Codice" CODTAB
@@ -114,14 +163,49 @@ BEGIN
   CHECKTYPE NORMAL
 END
 
+STRING F_OPERATORE 16
+BEGIN
+  PROMPT 1 7 "Operatore "
+  USE DIP
+  INPUT CODTAB F_OPERATORE
+  DISPLAY "Codice" CODTAB
+  DISPLAY "Cognome@40" S0[1,40]
+  DISPLAY "Nome@30" S0[41,70]
+  OUTPUT F_OPERATORE CODTAB
+  OUTPUT F_COGNOME S0[1,40]
+  OUTPUT F_NOME S0[41,70]
+  CHECKTYPE NORMAL
+  FIELD OPERATORE
+END
+
+STRING F_COGNOME 40 25
+BEGIN
+  PROMPT 30 7 ""
+  USE DIP KEY 2
+  INPUT S0[1,40] F_COGNOME
+  INPUT S0[41,70] F_NOME
+  DISPLAY "Cognome@40" S0[1,40]
+  DISPLAY "Nome@30" S0[41,70]
+  DISPLAY "Codice" CODTAB
+  COPY OUTPUT F_OPERATORE
+  CHECKTYPE SEARCH
+END
+
+STRING F_NOME 30 18
+BEGIN
+  PROMPT 59 7 ""
+  COPY ALL F_COGNOME
+  CHECKTYPE SEARCH
+END
+
 GROUPBOX DLG_NULL 78 4
 BEGIN
-  PROMPT 1 7 "@bOrdine di produzione"
+  PROMPT 1 8 "@bOrdine"
 END
 
 STRING F_CODNUM 4
 BEGIN
-  PROMPT 2 8 "Numerazione "
+  PROMPT 2 9 "Numerazione "
   USE %NUM
   INPUT CODTAB F_CODNUM
   DISPLAY "Codice" CODTAB
@@ -135,7 +219,7 @@ END
 
 STRING F_DESCRNUM 50
 BEGIN
-  PROMPT 24 8 ""
+  PROMPT 24 9 ""
   USE %NUM KEY 2
   INPUT S0 F_DESCRNUM
   DISPLAY "Descrizione@50" S0
@@ -145,7 +229,7 @@ END
 
 NUMBER F_ANNO 4
 BEGIN
-  PROMPT 2 9 "Anno        "
+  PROMPT 2 10 "Anno        "
   FLAGS "U"
   CHECKTYPE REQUIRED
   FIELD ANNO
@@ -153,7 +237,7 @@ END
 
 LISTBOX F_PROVV 11
 BEGIN
-  PROMPT 24 9 ""
+  PROMPT 24 10 ""
   ITEM "D|Definitivo "
   ITEM "P|Provvisorio"
   FIELD PROVV
@@ -161,134 +245,56 @@ END
 
 NUMBER F_NDOC 7
 BEGIN
-  PROMPT 43 9 "Numero "
-  USE LF_DOC           
+  PROMPT 43 10 "Numero "
+  USE LF_RIGHEDOC SELECT CODART==#F_CODART
   INPUT PROVV F_PROVV SELECT
   INPUT ANNO F_ANNO SELECT
   INPUT CODNUM F_CODNUM SELECT
   INPUT NDOC F_NDOC
-  DISPLAY "Num." CODNUM
-  DISPLAY "Anno" ANNO
-  DISPLAY "Provv" PROVV
-  DISPLAY "Tipo" TIPODOC
-  DISPLAY "N.Doc. " NDOC
-  DISPLAY "Stato@R" STATO
-  DISPLAY "Data\ndocumento" DATADOC
+  INPUT NRIGA F_NRIGA
+  DISPLAY "N.Doc.@7" NDOC
+  DISPLAY "Riga" NRIGA
+  DISPLAY "Descrizione@50" DESCR
+	DISPLAY "Articolo@20" CODARTMAG
   OUTPUT F_NDOC NDOC
-  OUTPUT F_PROVV PROVV
-  CHECKTYPE NORMAL
+  OUTPUT F_NRIGA NRIGA
   FIELD NDOC
 END
 
 NUMBER F_NRIGA 3
 BEGIN
-  PROMPT 66 9 "Riga "
-  USE LF_RIGHEDOC
-  INPUT PROVV F_PROVV SELECT
-  INPUT ANNO F_ANNO SELECT
-  INPUT CODNUM F_CODNUM SELECT
-  INPUT NDOC F_NDOC SELECT
-  INPUT NRIGA F_NRIGA
-  DISPLAY "Riga" NRIGA
-  DISPLAY "Descrizione@50" DESCR
-  OUTPUT F_NRIGA NRIGA
-  CHECKTYPE NORMAL
+  PROMPT 66 10 "Riga "
+	COPY ALL F_NDOC
+  CHECKTYPE SEARCH
   FIELD NRIGA
 END
 
-GROUPBOX DLG_NULL 38 3
-BEGIN
-  PROMPT 1 11 "@bInizio produzione"
-END
-
-DATA F_DATAINI
-BEGIN
-  PROMPT 2 12 "Data "
-  CHECKTYPE REQUIRED
-  FLAGS "D"
-END
-
-STRING F_ORAINI 2
-BEGIN
-  PROMPT 22 12 "Ora "
-  FLAGS "U"
-  NUM_EXPR #F_ORAINI<24
-  FIELD ORAPROD[1,2]
-END
-
-STRING F_MININI 2
-BEGIN
-  PROMPT 29 12 ":"
-  NUM_EXPR #F_MININI<60
-  FIELD ORAPROD[3,4]
-END
-
-STRING F_SECINI 2
-BEGIN
-  PROMPT 33 12 ":"
-  NUM_EXPR #F_SECINI<60
-  FIELD ORAPROD[5,6]
-END
-
-GROUPBOX DLG_NULL 38 3
-BEGIN
-  PROMPT 41 11 "@bFine produzione"
-END
-
-DATA F_DATAFIN
-BEGIN
-  PROMPT 42 12 "Data "
-  FIELD DATAFINE
-END
-
-STRING F_ORAFIN 2
-BEGIN
-  PROMPT 62 12 "Ora "
-  NUM_EXPR #F_ORAFIN<24
-  FIELD ORAFINE[1,2]
-END
-
-STRING F_MINFIN 2
-BEGIN
-  PROMPT 69 12 ":"
-  NUM_EXPR #F_MINFIN<60
-  FIELD ORAFINE[3,4]
-END
-
-STRING F_SECFIN 2
-BEGIN
-  PROMPT 73 12 ":"
-  NUM_EXPR #F_SECFIN<60
-  FIELD ORAFINE[5,6]
-END
-
 NUMBER F_QTA 15 5
 BEGIN
-  PROMPT 1 14 "Quantita' prodotta "
+  PROMPT 1 13 "Quantita' prodotta "
   FIELD QTA
 END
 
 BOOLEAN F_CHIUSO
 BEGIN
-  PROMPT 42 14 "Lotto chiuso"
+  PROMPT 38 13 "Lotto chiuso"
   FIELD CHIUSO
 END
 
-
-BUTTON F_DATALOG 10 2
+NUMBER F_SCARTO 15 5
 BEGIN
-  PROMPT 67 14 ""
-  PICTURE 20001
+  PROMPT 1 14 "Scarto di produz.  "
+  FIELD SCARTO
 END
 
 GROUPBOX DLG_NULL 78 4
 BEGIN
-  PROMPT 1 16 "@bBolla di produzione"
+  PROMPT 1 15 "@bBolla di produzione"
 END
 
 STRING F_CODNUMP 4
 BEGIN
-  PROMPT 2 17 "Numerazione "
+  PROMPT 2 16 "Numerazione "
   USE %NUM
   INPUT CODTAB F_CODNUMP
   DISPLAY "Codice" CODTAB
@@ -303,7 +309,7 @@ END
 
 STRING F_DESCRNUMP 50
 BEGIN
-  PROMPT 24 17 ""
+  PROMPT 24 16 ""
   USE %NUM KEY 2
   INPUT S0 F_DESCRNUMP
   DISPLAY "Descrizione@50" S0
@@ -315,7 +321,7 @@ END
 
 NUMBER F_ANNOP 4
 BEGIN
-  PROMPT 2 18 "Anno        "
+  PROMPT 2 17 "Anno        "
   FLAGS "UD"
   FIELD ANNOP
   GROUP GR_BOLPROD
@@ -323,7 +329,7 @@ END
 
 LISTBOX F_PROVVP 11
 BEGIN
-  PROMPT 24 18 ""
+  PROMPT 24 17 ""
   ITEM "D|Definitivo "
   ITEM "P|Provvisorio"
   FLAGS "D"
@@ -333,30 +339,15 @@ END
 
 NUMBER F_NDOCP 7
 BEGIN
-  PROMPT 43 18 "Numero "
-  USE LF_DOC           
-  INPUT PROVV F_PROVVP SELECT
-  INPUT ANNO F_ANNOP SELECT
-  INPUT CODNUM F_CODNUMP SELECT
-  INPUT NDOC F_NDOCP
-  DISPLAY "Num." CODNUM
-  DISPLAY "Anno" ANNO
-  DISPLAY "Provv" PROVV
-  DISPLAY "Tipo" TIPODOC
-  DISPLAY "N.Doc. " NDOC
-  DISPLAY "Data\ndocumento" DATADOC
-  OUTPUT F_NDOCP NDOC
-  OUTPUT F_PROVVP PROVV
-  CHECKTYPE NORMAL
+  PROMPT 43 17 "Numero "
   FLAGS "D"
   FIELD NDOCP
-  GROUP GR_BOLPROD
 END
 
 NUMBER F_NRIGAP 3
 BEGIN
-  PROMPT 66 18 "Riga "
-  USE LF_RIGHEDOC
+  PROMPT 66 17 "Riga "
+  USE LF_RIGHEDOC SELECT CODART==#F_CODART
   INPUT PROVV F_PROVVP SELECT
   INPUT ANNO F_ANNOP SELECT
   INPUT CODNUM F_CODNUMP SELECT
@@ -364,6 +355,7 @@ BEGIN
   INPUT NRIGA F_NRIGAP
   DISPLAY "Riga" NRIGA
   DISPLAY "Descrizione@50" DESCR
+  OUTPUT F_NDOCP NDOC
   OUTPUT F_NRIGAP NRIGA
   CHECKTYPE NORMAL
   FLAGS "D"
@@ -371,6 +363,159 @@ BEGIN
   GROUP GR_BOLPROD
 END
 
+
 ENDPAGE
 
-ENDMASK
\ No newline at end of file
+PAGE "Tempi" -1 -1 72 6
+
+GROUPBOX DLG_NULL 78 5
+BEGIN
+  PROMPT 1 0 ""
+END
+
+STRING DLG_NULL 20
+BEGIN
+  PROMPT 2 1 "Articolo        "  
+  FLAGS "UD"
+  GROUP 11
+END
+
+STRING DLG_NULL 50
+BEGIN
+  PROMPT 2 2 "Descrizione     "
+  FLAGS "UD"
+  GROUP 12
+END
+
+DATE DLG_NULL
+BEGIN
+  PROMPT 2 3 "Data consegna   "
+  FLAGS "D"
+  GROUP 13
+END
+
+NUMBER DLG_NULL 3
+BEGIN
+  PROMPT 42 3 "Progressivo del giorno "
+  FLAGS "UD"
+  GROUP 14
+END
+
+SPREADSHEET F_TEMPI 78
+BEGIN
+  PROMPT 1 5 "Tempi"
+  ITEM "Data inizio"
+  ITEM "Ora"
+  ITEM "Minuto"
+  ITEM "Secondo"
+  ITEM "Data fine@10"
+  ITEM "Ora"
+  ITEM "Minuto"
+  ITEM "Secondo"
+  ITEM "Quantit� prodotta"
+  ITEM "Scarto@15"
+END
+
+ENDPAGE
+
+ENDMASK
+
+PAGE "Tempi" -1 -1 80 11
+
+GROUPBOX DLG_NULL 38 3
+BEGIN
+  PROMPT 1 2 "@bInizio produzione"
+END
+
+DATA FR_DATAINI
+BEGIN
+  PROMPT 2 3 "Data "
+  CHECKTYPE REQUIRED
+END
+
+STRING FR_ORAINI 2
+BEGIN
+  PROMPT 22 3 "Ora "
+  FLAGS "U"
+  NUM_EXPR #F_ORAINI<24
+  FIELD ORAPROD[1,2]
+END
+
+STRING FR_MININI 2
+BEGIN
+  PROMPT 29 3 ":"
+  NUM_EXPR #F_MININI<60
+  FIELD ORAPROD[3,4]
+END
+
+STRING FR_SECINI 2
+BEGIN
+  PROMPT 33 3 ":"
+  NUM_EXPR #F_SECINI<60
+  FIELD ORAPROD[5,6]
+END
+
+GROUPBOX DLG_NULL 38 3
+BEGIN
+  PROMPT 41 2 "@bFine produzione"
+END
+
+DATA FR_DATAFIN
+BEGIN
+  PROMPT 42 3 "Data "
+  FIELD DATAFINE
+END
+
+STRING FR_ORAFIN 2
+BEGIN
+  PROMPT 62 3 "Ora "
+  NUM_EXPR #F_ORAFIN<24
+  FIELD ORAFINE[1,2]
+END
+
+STRING FR_MINFIN 2
+BEGIN
+  PROMPT 69 3 ":"
+  NUM_EXPR #F_MINFIN<60
+  FIELD ORAFINE[3,4]
+END
+
+STRING FR_SECFIN 2
+BEGIN
+  PROMPT 73 3 ":"
+  NUM_EXPR #F_SECFIN<60
+  FIELD ORAFINE[5,6]
+END
+
+NUMBER FR_QTA 15 5
+BEGIN
+  PROMPT 1 5 "Quantita' prodotta "
+  FIELD QTA
+END
+
+NUMBER FR_SCARTO 15 5
+BEGIN
+  PROMPT 1 7 "Scarto di produz.  "
+  FIELD SCARTO
+END
+
+BUTTON DLG_OK 10 2
+BEGIN
+  PROMPT -13 -1 ""
+END
+
+BUTTON DLG_CANCEL 10 2
+BEGIN
+  PROMPT -23 -1 ""
+END
+
+BUTTON DLG_DELREC 10 2
+BEGIN
+  PROMPT -33 -1 "Elimina"
+  MESSAGE EXIT,K_DEL
+END
+
+ENDPAGE
+
+ENDMASK
+
diff --git a/mr/mr0500b.h b/mr/mr0500b.h
new file mode 100755
index 000000000..5ac2ea266
--- /dev/null
+++ b/mr/mr0500b.h
@@ -0,0 +1,5 @@
+#define F_FILE        101
+#define F_PROFILO     102
+#define F_SAVE        103
+#define F_ONLY_ERRORS 104
+
diff --git a/mr/mr0500b.uml b/mr/mr0500b.uml
new file mode 100755
index 000000000..9d2df1d36
--- /dev/null
+++ b/mr/mr0500b.uml
@@ -0,0 +1,41 @@
+#include "mr0500b.h"
+
+PAGE "Lettura terminale portatile" -1 -1 80 8
+
+STRING F_FILE 128 40
+BEGIN
+  PROMPT 1 2 "File     "
+  FLAGS "B"
+  CHECKTYPE REQUIRED
+END
+
+BOOLEAN F_SAVE 
+BEGIN
+	PROMPT 1 4 "Archivia il file sorgente"
+END
+
+BOOLEAN F_ONLY_ERRORS 
+BEGIN
+	PROMPT 40 4 "Visualizza solo gli errori"
+END
+
+STRING F_PROFILO 70 50
+BEGIN
+	PROMPT 1 -3 "Profilo  "
+	PSELECT
+END
+
+BUTTON DLG_OK 10 2
+BEGIN
+  PROMPT -12 -1 ""
+END
+
+BUTTON DLG_CANCEL 10 2
+BEGIN
+  PROMPT -22 -1 ""
+END   
+
+ENDPAGE
+
+ENDMASK
+
diff --git a/mr/mr0500c.h b/mr/mr0500c.h
new file mode 100755
index 000000000..0c613b2b2
--- /dev/null
+++ b/mr/mr0500c.h
@@ -0,0 +1,4 @@
+#define F_CODICE_EL   101
+#define F_DATA_EL     102
+#define F_DESC_EL     103
+
diff --git a/mr/mr0500c.uml b/mr/mr0500c.uml
new file mode 100755
index 000000000..f0957aef3
--- /dev/null
+++ b/mr/mr0500c.uml
@@ -0,0 +1,49 @@
+#include "mr0500c.h"
+
+PAGE "Elaborazione produzione" -1 -1 80 8
+
+STRING F_CODICE_EL 8
+BEGIN
+  PROMPT 2 1 "Codice elaborazione"
+  FLAG "U"
+  USE %ELD SELECT I0 == 6
+  INPUT CODTAB F_CODICE_EL
+  DISPLAY "Codice" CODTAB
+  DISPLAY "Descrizione@55" S0
+  OUTPUT F_CODICE_EL CODTAB
+  OUTPUT F_DESC_EL S0
+  CHECKTYPE REQUIRED
+  WARNING "E' necessario specificare il codice elaborazione"
+END
+
+STRING F_DESC_EL 50 30
+BEGIN
+  PROMPT 35 1 ""
+  USE %ELD KEY 2 SELECT I0 == 6
+  INPUT S0 F_DESC_EL
+  DISPLAY "Descrizione@55" S0
+  DISPLAY "Codice" CODTAB
+  COPY OUTPUT F_CODICE_EL
+END
+
+DATE F_DATA_EL
+BEGIN
+  PROMPT 2 3 "Data elaborazione  "
+  CHECKTYPE REQUIRED
+  WARNING "La data di inizio intervallo e' obbligatoria"
+END
+
+BUTTON DLG_OK 10 2
+BEGIN
+  PROMPT -12 -1 ""
+END
+
+BUTTON DLG_CANCEL 10 2
+BEGIN
+  PROMPT -22 -1 ""
+END   
+
+ENDPAGE
+
+ENDMASK
+
diff --git a/mr/mr1100.cpp b/mr/mr1100.cpp
index 4139a4b3d..febbea10a 100755
--- a/mr/mr1100.cpp
+++ b/mr/mr1100.cpp
@@ -2,6 +2,7 @@
 #include <applicat.h>
 #include <form.h>
 #include <relation.h>
+#include <reprint.h>
 #include <printer.h>
 #include <progind.h>
 
@@ -76,7 +77,7 @@ public:
 
 _TCapacitaLinea::_TCapacitaLinea()
 {
-  for (int i = 0; i<LAST_BUCKET-1; i++)
+  for (int i = 0; i < LAST_BUCKET-1; i++)
   {
     _cap_min.add(new real);
     _cap_max.add(new real);
@@ -130,7 +131,9 @@ TMRP_rep_record& TMRP_rep_record_array::operator[](int b)
 class TMRP_rep_line : public TSortable
 {
   TCodice_articolo _codart;
-  TString16 _giac, _imp, _lin, _um;
+  TString16 _giac;
+  TString8 _imp, _lin;
+  TString4 _um;
 
   TMRP_rep_record_array _bucket;
 
@@ -272,7 +275,6 @@ TMRP_rep_line* TMRP_rep_lines::find(const TCodice_articolo& codart,
 ///////////////////////////////////////////////////////////
 // MRP report generator mask
 ///////////////////////////////////////////////////////////
-
 class TRepgen_mask : public TCalendar_mask
 {
 protected:
@@ -284,6 +286,10 @@ protected:
 
 public:
   int round_date(TDate& date, bool up) const;
+	int get_bucket_size() const { return get_int(F_BUCKET) * get_int(F_DAYXBUCK);}
+	const TDate start_date() const { return get_date(F_DADATA);} 
+	const TDate end_date() const { return get_date(F_ADATA);} 
+	int last_bucket() { TDate d(end_date()); return round_date(d, true);}
   bool elabora() const;
   TRepgen_mask();
   virtual ~TRepgen_mask() { }
@@ -317,23 +323,47 @@ bool TRepgen_mask::test_tipodoc_num(const  TSheet_field &sheet_num ,const  TShee
 int TRepgen_mask::round_date(TDate& date, bool up) const
 {
   // Dimensione del bucket in giorni
-  int bucket_size = get_int(F_BUCKET) * 7;
-  if (bucket_size < 7) bucket_size = 7;
-
-  // Riporta la data al primo lunedi prima dell'inizio
-  TDate inizio = get(F_DADATA);
-  const int wday = inizio.wday();
-  if (wday > 1) inizio -= wday-1;
-
-  // Calcola il bucket di appartenenza
-  const int days = int(date - inizio);
-  const int bucket = days / bucket_size;
-
-  if (up) // Arrotonda alla fine del bucket
-    date = inizio + long((bucket+1) * bucket_size - 1);
-  else    // Arrotonda all'inizio del bucket  
-    date = inizio + long(bucket * bucket_size);
+	const int bucket_size = get_bucket_size();
 
+  TDate inizio(start_date());
+  int bucket;
+  if (bucket_size == 31) // mese solare
+  {
+    if (up)
+    {
+      date.set_end_month();
+      int wday = date.wday();
+      wday = (7-wday) % 7;
+      if (wday<0)
+        date += wday;
+    }
+    else
+      date.set_day(1);
+    bucket = (date.year()-inizio.year())*12 + date.month() - inizio.month();
+    if (bucket < 0)
+			bucket = 0;
+  }
+  else
+  {
+    if (bucket_size > 1) // non vado a giorni
+    {
+      const int wday = inizio.wday();
+      if (wday > 1) inizio -= wday-1;
+    }
+    // Calcola il bucket di appartenenza
+    const int days = int(date - inizio);
+    
+		bucket = days / bucket_size;
+		if (bucket < 0)
+      bucket = 0;
+    else
+			if (bucket > LAST_BUCKET)
+				bucket = LAST_BUCKET;
+    if (up) // Arrotonda alla fine del bucket
+      date = inizio + long((bucket+1 )* bucket_size - 1 /*-  get_int(F_LASTWRKDAY)*/);
+    else    // Arrotonda all'inizio del bucket  
+      date = inizio + long(bucket * bucket_size);
+  }
   return bucket;
 }
 
@@ -353,8 +383,8 @@ void TRepgen_mask::calcola_capacita(TAssoc_array& capacita) const
     return;
 
   const bool carico_uomo = get_bool(F_MANLOAD);
-  const TDate df(get_date(F_DADATA));
-  const TDate dt(get_date(F_ADATA));
+  const TDate df(start_date());
+  const TDate dt(end_date());
   TDate wd1,wd2;
   TString16 codimp;
   
@@ -377,7 +407,8 @@ void TRepgen_mask::calcola_capacita(TAssoc_array& capacita) const
     {
       wd2 = wd1;
       const int bucket = round_date(wd2, FALSE); // da 0 a 10 al massimo
-      if (bucket > 10)
+      
+			if (bucket > 10)
         break; // Fine
       real & v1 = (real&) cap_min[bucket];
       v1 += carico_uomo ? mc.add_oreuomo(v1, wd1)   : mc.add_oremacchina(v1, wd1);
@@ -394,14 +425,15 @@ bool TRepgen_mask::elabora() const
   const TRectype& riga = cur.curr();
   TRectype filter_fr(riga), filter_to(riga);
 
-  const TDate date_fr = get(F_DADATA);
+  const TDate date_fr(start_date());
   const int year_fr = date_fr.year();
-  TDate date_to = get(F_ADATA);
+  TDate  date_to(end_date());
   const int year_to = date_to.year();
-  const int bucket_size = get_int(F_BUCKET) * 7;
+	const int bucket_size = get_bucket_size();
   const TExplosion_grouping raggr = (TExplosion_grouping)get_int(F_RAGGRUM);
   const tipo_valore ts = (tipo_valore) get_int(F_VAL2PRINT);
   const bool carico_uomo = get_bool(F_MANLOAD);
+
   const int last_bucket = round_date(date_to,TRUE)+1;
   
   TString16 ws;
@@ -441,84 +473,73 @@ bool TRepgen_mask::elabora() const
       const TCodice_articolo art = riga.get(RDOC_CODARTMAG);
       if (art.not_empty())
       {
-        TDate datacons = riga.get(RDOC_DATACONS);
-        // Seleziona tutte le righe! Altrimenti LAST_BUCKET non viene mai settato 
-        //if (datacons <= date_to)
+        real qta;
+        if (!riga.get_bool(RDOC_RIGAEVASA))
         {
-          real qta;
-          if (!riga.get_bool(RDOC_RIGAEVASA))
+          qta = riga.get_real(RDOC_QTA);
+          qta -= riga.get_real(RDOC_QTAEVASA);
+        }
+        // Seleziona le righe articolo non ancora evase
+        if (qta > ZERO)
+        {
+          const TString16 liv = riga.get(RDOC_LIVELLO); 
+          const TString16 imp = riga.get(RDOC_IMPIANTO); 
+          const TString16 lin = riga.get(RDOC_LINEA); 
+          const TCodice_um um = riga.get(RDOC_UMQTA);
+          TQuantita q(art, um, qta);
+		      TDate datacons = riga.get(RDOC_DATACONS);
+          
+          int bucket = round_date(datacons, FALSE);
+          if (bucket < 0) 
+            bucket = 0;
+          if (bucket > last_bucket) 
+            bucket = last_bucket;
+
+          // Calcoli per carico
+          if (ts == carico)
           {
-            qta = riga.get_real(RDOC_QTA);
-            qta -= riga.get_real(RDOC_QTAEVASA);
-          }
-          // Seleziona le righe articolo non ancora evase
-          if (qta > ZERO)
-          {
-            const TString16 liv = riga.get(RDOC_LIVELLO); 
-            const TString16 imp = riga.get(RDOC_IMPIANTO); 
-            const TString16 lin = riga.get(RDOC_LINEA); 
-            const TCodice_um um = riga.get(RDOC_UMQTA);
+            distinta.set_root(riga);
+            real ore,tot;
             
-            TQuantita q(art, um, qta);
-            int bucket = 0;
-
-            if (datacons >= date_fr) 
+            TRiga_esplosione * llav = distinta.first_labor(lav_array, raggr);
+            TLavorazione * lavorazione = TDistinta_tree::find_labor(llav);
+            
+            while (llav)
             {
-              bucket = round_date(datacons, FALSE) + 1;
-              if (bucket > last_bucket)
-                bucket = LAST_BUCKET;
+              const int linea = lavorazione->find_linea(lin);
+              
+              const real prod_linea = lavorazione->produttiv_linea(linea);
+              ore = (llav->val() * lavorazione->um_temporale().converti_in_ore()) / prod_linea;
+              if (carico_uomo)
+                ore *= lavorazione->numpers_linea(linea);
+              
+              //rep.qta(bucket) += ore;
+              tot += ore;
+              llav = distinta.next_labor(lav_array);
             }
-
-            // Calcoli per carico
-            if (ts == carico)
+            
+            if (tot > ZERO)
             {
-              distinta.set_root(riga);
-              real ore,tot;
-              
-              TRiga_esplosione * llav = distinta.first_labor(lav_array, raggr);
-              TLavorazione * lavorazione = TDistinta_tree::find_labor(llav);
-              
-              while (llav)
-              {
-                const int linea = lavorazione->find_linea(lin);
-                
-                const real prod_linea = lavorazione->produttiv_linea(linea);
-                ore = (llav->val() * lavorazione->um_temporale().converti_in_ore()) / prod_linea;
-                if (carico_uomo)
-                  ore *= lavorazione->numpers_linea(linea);
-                
-                //rep.qta(bucket) += ore;
-                tot += ore;
-                llav = distinta.next_labor(lav_array);
-              }
-              
-              if (tot > ZERO)
-              {
-                TMRP_rep_line& rep = *articles.find(art, liv, imp, lin, ws, TRUE);
-                rep.qta(bucket) += tot;
-              }
-              
-              
-              // Sbatte nella cache le linee di cui dopo calcolera' le capacita' minime e massime
-              // In modo che il calcolo venga effettuato una volta sola per ogni linea.
-              if (capacita.objptr(lin) == NULL)
-                capacita.add(lin, new _TCapacitaLinea); // Vuoto per ora... lo riempie poco piu' giu'
+              TMRP_rep_line& rep = *articles.find(art, liv, imp, lin, ws, TRUE);
+              rep.qta(bucket) += tot;
             }
-            else // Produzione articoli nel tempo & scheduling linee
+            
+            
+            // Sbatte nella cache le linee di cui dopo calcolera' le capacita' minime e massime
+            // In modo che il calcolo venga effettuato una volta sola per ogni linea.
+            if (capacita.objptr(lin) == NULL)
+              capacita.add(lin, new _TCapacitaLinea); // Vuoto per ora... lo riempie poco piu' giu'
+          }
+          else // Produzione articoli nel tempo & scheduling linee
+          {
+            TMRP_rep_line& rep = *articles.find(art, liv, imp, lin, q.um(), TRUE);
+            switch (raggr)
             {
-              TMRP_rep_line& rep = *articles.find(art, liv, imp, lin, q.um(), TRUE);
-              switch (raggr)
-              {
-               case RAGGR_EXP_UMBASE:
-                  q.convert2umbase();
-                  break;
-               case RAGGR_EXP_UMDIST:
-                  q.convert2umdist();
-                  break;
-               default: break;   
-              }
-              rep.qta(bucket) += q.val();
+             case RAGGR_EXP_UMBASE: q.convert2umbase(); break;
+             case RAGGR_EXP_UMDIST: q.convert2umdist(); break;
+             default: break;   
             }
+            rep.qta(bucket) += q.val();
           }
         }
       }
@@ -533,34 +554,59 @@ bool TRepgen_mask::elabora() const
   TProgind pi(total, TR("Generazione file"), FALSE, TRUE);
 
   TMask_field& fld = field(F_FILENAME);
-  TFilename filename = fld.get();
 
-  if (filename.empty())
-    filename.temp("mrprep");
+  TLocalisamfile* rep = NULL;
 
-  fld.set(filename);
+  if (fld.empty())
+  {
+    TSystemisamfile mrprep(LF_MRPREP);
+    mrprep.zap();
 
-  filename.insert("%");
-
-  TIsamtempfile rep(LF_MRPREP, filename);
-  
+    rep = new TLocalisamfile(LF_MRPREP);
+  }
+  else
+  {
+    TFilename filename = fld.get();
+    if (filename.empty())
+      filename.temp("mrprep");
+    fld.set(filename);
+    filename.insert("%");
+    rep = new TIsamtempfile(LF_MRPREP, filename);
+  }
+    
   // Scrive la testata (Record tipo "H");
-  rep.put("TIPO","H");
-  rep.put("CODART", date_fr.string());
-  rep.put("LIVELLO", get(F_ADATA));
-  rep.put("IMPIANTO", bucket_size);
-  rep.put("LINEA", ts == quantita  ? "Q" : "C");
-  rep.write();
+  rep->put("TIPO","H");
+  rep->put("CODART", date_fr.string());
+  rep->put("LIVELLO", get(F_ADATA));
+  rep->put("IMPIANTO", bucket_size);
+  rep->put("LINEA", ts == quantita  ? "Q" : "C");
+
+  // Scrive le date nelle quantita' dei buckets
+  TDate fd = date_fr; 
+  --fd; 
+  rep->put("QTAFIRST", fd.string(ANSI));
+  ++fd;
+  for (int b = 1; b <= last_bucket; b++)
+  {
+    TString8 fldname; fldname.format("QTA%d", b);
+    rep->put(fldname, fd.string(ANSI));
+		fd += bucket_size;
+  }
+  rep->put("QTALAST", fd.string(ANSI));
+  
+  rep->write();
   
   for (long i = 0; i < total; i++)
   {
     pi.addstatus(1);
-    articles[i].fill(rep.curr(), ts == carico ? &capacita : NULL);
-    int err = rep.write();
+    articles[i].fill(rep->curr(), ts == carico ? &capacita : NULL);
+    int err = rep->write();
     if (err != NOERR)
-      rep.rewrite();
+      rep->rewrite();
   }
-  return rep.good();
+  delete rep;
+  
+  return true;
 }
 
 bool TRepgen_mask::on_field_event(TOperable_field& o, TField_event e, long jolly)
@@ -568,18 +614,18 @@ bool TRepgen_mask::on_field_event(TOperable_field& o, TField_event e, long jolly
   switch(o.dlg())
   {
   case F_DADATA:
-    if (e == fe_modify)
-      round_field(o, FALSE);
+    if (e == fe_modify || e == fe_close)
+      round_field(o, false);
     break;
   case F_ADATA:
-    if (e == fe_modify)
-      round_field(o, TRUE);
+    if (e == fe_modify || e == fe_close)
+      round_field(o, true);
     break;
   case F_BUCKET:
     if (e == fe_modify)
     {
-      round_field(field(F_DADATA), FALSE);
-      round_field(field(F_ADATA), TRUE);
+      round_field(field(F_DADATA), false);
+      round_field(field(F_ADATA), true);
     }
     break;
   case F_NUMERAZIONI:
@@ -757,8 +803,11 @@ public:
 
 bool TMRP_repgen::create()
 {
+  open_files(LF_MRPREP, LF_RIGHEDOC, LF_ANAMAG, LF_TAB, 0);
+
+  TConfig ini(CONFIG_DITTA, "mr");
+
   _m = new TRepgen_mask;
-  open_files(LF_MRPREP, 0);
   _codgiac = new  TCodgiac_livelli;
   if (!_codgiac->enabled())
     _m->hide(F_LIVDET);
@@ -776,73 +825,83 @@ bool TMRP_repgen::destroy()
 void TMRP_repgen::set_buckets_description()
 {
   TString descr;
-  TDate fd = _m->get_date(F_DADATA);
-  TDate td = _m->get_date(F_ADATA);
-  
+	TRepgen_mask & mask = *_m;
+  TDate fd(mask.start_date());
   TConfig ini(CONFIG_DITTA, "mr");
   const bool week_complete = ini.get_bool("WEEKCOMPLETE");
-  
-  int bucket_size = _m->get_int(F_BUCKET) * 7;
-  if (bucket_size < 7) bucket_size = 7;
-  
+	const int bucket_size = _m->get_bucket_size();
   int weekd, yeard;
-  
   const short first_id = 3;
-  const short last_id  = 15;
-  --fd;
-  descr.format(FR("\nAl  %s"), (const char*)fd);
-  if (bucket_size == 7)
-  {
-    fd.get_week_year(weekd, yeard, week_complete);
-    descr << TR("\nSett. ") << weekd << ' ' << yeard;
-  }
-  _form->find_field('B', odd_page, first_id).set_col_head(descr);
-  TDate wd;
-  for (;fd <= td;)
+  const short last_id = 15;
+	int last_bucket = mask.last_bucket();
+
+  if (last_bucket >= LAST_BUCKET)
+		last_bucket = LAST_BUCKET - 1;
+	--fd;
+	descr.cut(0);
+	if (bucket_size != 1)
+		descr << "\n";
+	descr  << TR("Al") << "  " << fd.string();
+	if (bucket_size == 7)
+	{
+		fd.get_week_year(weekd, yeard, week_complete);
+		descr << "\n" << TR("Sett.") << " " << weekd << ' ' << yeard;
+	}
+  TForm_item & ff = _form->find_field('B', odd_page, first_id);
+	ff.set_col_head(descr);
+  for (short i = 1; i <= (short) last_bucket; i++)
   {
     ++fd;
-    descr.format(FR("Dal %s\nAl  "), (const char*)fd);
-    fd += bucket_size-1;
-    wd = fd;
-    descr << (const char*)fd;
-    const short id = first_id+_m->round_date(wd,FALSE)+1;
-    if (id >= last_id)
-      break;
-    if (bucket_size == 7)
-    {
-      wd.get_week_year(weekd, yeard, week_complete);
-      descr << TR("\nSett. ") << weekd << ' ' << yeard;
-    }
-    _form->find_field('B', odd_page, id).set_col_head(descr);
+		descr.cut(0);
+		if (bucket_size != 1)
+			descr << FR("Dal"); fd.string();
+		descr << " " << fd.string() << " ";
+		if (bucket_size != 1)
+		{
+			fd += bucket_size-1;
+			descr << "\n" << FR("Al") << "  " << fd.string();
+			if (bucket_size == 7)
+			{
+				fd.get_week_year(weekd, yeard, week_complete);
+				descr << "\n" << TR("Sett.") << " " << weekd << ' ' << yeard;
+			}
+		}
+    TForm_item & fi = _form->find_field('B', odd_page, first_id + i);
+		fi.set_col_head(descr);
   }
-  descr.format(FR("Dal %s"), (const char*)wd);
-  if (bucket_size == 7)
-  {
-    wd.get_week_year(weekd, yeard, week_complete);
-    descr << TR("\n\nSett. ") << weekd << ' ' << yeard;
-  }
-  _form->find_field('B', odd_page, last_id).set_col_head(descr);
+	++fd;
+	descr.cut(0);
+	descr << FR("Dal ") << fd.string();
+	if (bucket_size == 7)
+	{
+		fd.get_week_year(weekd, yeard, week_complete);
+		descr << TR("\n\nSett. ") << weekd << ' ' << yeard;
+	}
+  TForm_item & lf = _form->find_field('B', odd_page, last_id);
+	lf.set_col_head(descr);
 }
 
 void TMRP_repgen::set_buckets()
 {
   TString tmp;
-  TDate last_date = _m->get_date(F_ADATA);
 
   // Calcola l'ultimo bucket visibile: 
   // Il bucket iniziale e quello finale dovrebbero essere sempre visibili
-  const short last_bucket = _m->round_date(last_date,TRUE)+1;
+  const short last_bucket = _m->last_bucket();
 
   // Disabilita le colonne in base al numero di buckets da visualizzare
-  const short first_id = 4;   // Bucket  1
-  const short last_id  = 14;  // Bucket  11
+	if (last_bucket < LAST_BUCKET - 1)
+	{
+		const short first_id = 4;   // Bucket  1
+		const short last_id  = 14;  // Bucket  11
 
-  for (short id = first_id+last_bucket; id <= last_id; id++)
-     _form->find_field('B',odd_page,id).disable();
+		for (short id = first_id+last_bucket; id <= last_id; id++)
+			 _form->find_field('B',odd_page,id).disable();
 
-  // Nella stampa scheduling linee, non esiste un totale per linea/impianto ma per articolo/liv giacenza
-  for (id = first_id+last_bucket+100; id <= (last_id+100); id++)
-     _form->find_field('B',odd_page,id).disable();
+		// Nella stampa scheduling linee, non esiste un totale per linea/impianto ma per articolo/liv giacenza
+		for (id = first_id+last_bucket+100; id <= (last_id+100); id++)
+			 _form->find_field('B',odd_page,id).disable();
+	}
 
   set_buckets_description();
   
@@ -862,7 +921,7 @@ void TMRP_repgen::set_buckets()
       sections = tl ? "" : "ARTICOLI|LIVELLI";
       break;
     case det_linea:
-      sections = tl ? "IMPIANTI" : "ARTICOLI|LIVELLI|IMPIANTI";
+			sections = tl ? "IMPIANTI" : "ARTICOLI|LIVELLI|IMPIANTI";
       break;
     default: break;
   }
@@ -881,35 +940,40 @@ void TMRP_repgen::set_buckets()
   if (tl && _m->get_bool(F_CAPACITA)) // Abilitato il calcolo capacita/carico linea?
   {
     _form->find_field('B', odd_page, 238).show();
-    const short lid = 240 + (last_bucket >= LAST_BUCKET ? 11 : last_bucket);
+    short lid = 240 + last_bucket;
+		if (lid > 250)
+			lid = 250;
     for (short id = 240; id<lid; id++)
       _form->find_field('B', odd_page, id).show();
   }
   
-  if (tl && _tipo_val == quantita) // Stampa scheduling, disabilita totali per linea/impianto)
-  {
-    // Abilita i campi per l'unita di misura sui totali per livello giac. e articolo
-    _form->find_field('B', odd_page, 2).show();
-    _form->find_field('B', odd_page, 302).show();
-    _form->find_field('B', odd_page, 402).show();
-    _form->find_field('B', odd_page, 502).show();
-    for (short id = 201; id <= 215; id++)
-      _form->find_field('B', odd_page, id).hide(); // Riga totale linea
-    for (id = 101; id <= 115; id++)
-      _form->find_field('B', odd_page, id).hide(); // Riga totale impianto
-  }
-  
-  if (!tl && _tipo_val == carico) // Stampa carico per articoli
-  {
-    // Nasconde la colonna delle unita' di misura.
-    // Il calcolo capacita' non ha senso e quindi viene omesso in
-    // stampa, sebbene sia possibile effettuarne il calcolo.
-    _form->find_field('B', odd_page, 2).hide();
-    _form->find_field('B', odd_page, 102).hide();
-    _form->find_field('B', odd_page, 202).hide();
-    _form->find_field('B', odd_page, 302).hide();
-    _form->find_field('B', odd_page, 402).hide();
-  }
+  if (tl)
+	{
+		if (_tipo_val == quantita) // Stampa scheduling, disabilita totali per linea/impianto)
+		{
+			// Abilita i campi per l'unita di misura sui totali per livello giac. e articolo
+			_form->find_field('B', odd_page, 2).show();
+			_form->find_field('B', odd_page, 302).show();
+			_form->find_field('B', odd_page, 402).show();
+			_form->find_field('B', odd_page, 502).show();
+			for (short id = 201; id <= 215; id++)
+				_form->find_field('B', odd_page, id).hide(); // Riga totale linea
+			for (id = 101; id <= 115; id++)
+				_form->find_field('B', odd_page, id).hide(); // Riga totale impianto
+		}
+	}
+  else
+		if (_tipo_val == carico) // Stampa carico per articoli
+		{
+			// Nasconde la colonna delle unita' di misura.
+			// Il calcolo capacita' non ha senso e quindi viene omesso in
+			// stampa, sebbene sia possibile effettuarne il calcolo.
+			_form->find_field('B', odd_page, 2).hide();
+			_form->find_field('B', odd_page, 102).hide();
+			_form->find_field('B', odd_page, 202).hide();
+			_form->find_field('B', odd_page, 302).hide();
+			_form->find_field('B', odd_page, 402).hide();
+		}
   
   // Prende il titolo della stampa dal nome profilo
   _form->find_field('H', odd_page,4).set(_m->get(DLG_PROFILE));
@@ -984,47 +1048,76 @@ void TMRP_repgen::set_form()
 
 void TMRP_repgen::main_loop()
 {
-  while (_m->run() != K_QUIT)
+	KEY k;
+  while ((k = _m->run()) != K_QUIT)
   {
     const bool use_file = _m->get_bool(F_USAFILE);
     if (use_file || _m->elabora())
     {
-      _tipo_ord       = (tipo_ordinamento) _m->get_int(F_ORDINAMENTO);
-      _tipo_val       = (tipo_valore)      _m->get_int(F_VAL2PRINT);
-      _livello    = _m->get_int(F_LIVDET);
-      TFilename fname(_m->get(F_FILENAME)); // Presente 24 ore su 24
-      fname.insert("%"); // e questo dove lo mettiamo?
-      const bool delfile = !_m->get_bool(F_GENREPORT) && !use_file;
+			if (k == K_ENTER)
+			{
+				TFilename report_name(_m->get(F_REPORT));
+				
+				if (report_name.empty())
+				{
+					_tipo_ord = (tipo_ordinamento) _m->get_int(F_ORDINAMENTO);
+					_tipo_val = (tipo_valore)      _m->get_int(F_VAL2PRINT);
+					_livello = _m->get_int(F_LIVDET);
+
+					const bool delfile = !_m->get_bool(F_GENREPORT) && !use_file;
       
-      if (delfile)
-        _m->reset(F_FILENAME);
-      // Utilizza questo file per la stampa del form
-      TIsamtempfile * report = new TIsamtempfile(LF_MRPREP,fname, FALSE, delfile);
-      TRelation* rel;
-      _dettaglio  = (tipo_dettaglio) _m->get_int(_tipo_ord == articolo ? F_DETTAGLIO1 : F_DETTAGLIO2);
-      _form = new TMRP_form(_tipo_ord == articolo ? "mr1100a" : "mr1100b", _codgiac, _livello);
-      rel = _form->relation();
-      rel->replace(report);
-      set_form();
+					if (delfile)
+					{
+						_m->reset(F_FILENAME);
+					}
+
+					// Utilizza questo file per la stampa del form   
+					_dettaglio  = (tipo_dettaglio) _m->get_int(_tipo_ord == articolo ? F_DETTAGLIO1 : F_DETTAGLIO2);
+					_form = new TMRP_form(_tipo_ord == articolo ? "mr1100a" : "mr1100b", _codgiac, _livello);
+					TRelation* rel = _form->relation();
+
+					if (!delfile)
+					{
+						TFilename fname(_m->get(F_FILENAME)); // Presente 24 ore su 24
+						fname.insert("%"); // e questo dove lo mettiamo?
+						TIsamtempfile * report = new TIsamtempfile(LF_MRPREP,fname, FALSE, delfile);
+						rel->replace(report);
+					}
+					set_form();
       
-      const int hh = 7;
-      const int fl = printer().formlen();
+					const int hh = 7;
+					const int fl = printer().formlen();
       
-      int rows[4];         // Righe orizzontali
-      rows[0] = hh-4;
-      rows[1] = hh;
-      rows[2] = fl;
-      rows[3] = 0;
-      _form->genera_intestazioni(odd_page, hh-3);
-      _form->genera_fincatura(odd_page, hh-4, fl, rows);
+					int rows[4];         // Righe orizzontali
+					rows[0] = hh-4;
+					rows[1] = hh;
+					rows[2] = fl;
+					rows[3] = 0;
+					_form->genera_intestazioni(odd_page, hh-3);
+					_form->genera_fincatura(odd_page, hh-4, fl, rows);
   
-      // stampa
-      if (_form->cursor()->items() > 0)
-        _form->print();
-      // report non va cancellato, poiche' ne viene fatta la sostituzione nella relazione del form
-      // quindi la delete viene gia' fatta alla distruzione di _form
-      delete _form;
-    }
+					// stampa
+					if (_form->cursor()->items() > 0)
+						_form->print();
+					// report non va cancellato, poiche' ne viene fatta la sostituzione nella relazione del form
+					// quindi la delete viene gia' fatta alla distruzione di _form
+					delete _form;
+					_form = NULL;
+				}
+				else
+				{
+					TReport_book book;
+					TReport rep; 
+					
+					if (rep.load(report_name))
+					{
+						book.add(rep);
+						if (book.pages() > 0)
+							book.print_or_preview();
+					}
+				}
+			}
+		}
   }
 }
 
diff --git a/mr/mr1100a.frm b/mr/mr1100a.frm
index 48de3e6ec..36b479b34 100755
--- a/mr/mr1100a.frm
+++ b/mr/mr1100a.frm
@@ -2,7 +2,7 @@
 // ed il carico articoli nel tempo ( non richiesta ma messa per completezza )
 
 
-USE LF_MRPREPORT
+USE LF_MRPREPORT KEY 2
 JOIN LF_ANAMAG INTO CODART==CODART
 JOIN IMP ALIAS 201 INTO CODTAB==IMPIANTO
 JOIN LNP ALIAS 202 INTO CODTAB==LINEA
@@ -51,7 +51,7 @@ END //HEADER
 
 SECTION BODY ODD 3 COLUMNWISE
 
-STRING 1 50
+STRING 1 50 2
 BEGIN
  SPECIAL STRINGA INTESTAZIONE "Articolo" "Articolo"
  SPECIAL NUMERO OFFSET "0" "Offset iniziale campo"
diff --git a/mr/mr1100a.h b/mr/mr1100a.h
index 0bb9a251f..f8314b511 100755
--- a/mr/mr1100a.h
+++ b/mr/mr1100a.h
@@ -26,6 +26,7 @@
 #define F_MANLOAD     224
 #define F_CAPACITA    225
 #define F_USAFILE     226
+#define F_DAYXBUCK    227
 #define F_YEAR        301 
 #define F_IMPIANTO    302
 #define F_LINEA       303
@@ -36,5 +37,7 @@
 #define F_DASTATO     103
 #define F_ASTATO      104
 
+#define F_REPORT      305
+
 #endif
 
diff --git a/mr/mr1100a.uml b/mr/mr1100a.uml
index a2809e1e1..48a7529e3 100755
--- a/mr/mr1100a.uml
+++ b/mr/mr1100a.uml
@@ -54,23 +54,27 @@ LIST F_BUCKETS 1 15
 BEGIN
   PROMPT 2 4 "Bucket temporale "
   ITEM "1|1 Settimana" 
-    MESSAGE DISABLE,F_BUCKET|COPY,F_BUCKET
+    MESSAGE SHOW,F_BUCKET|DISABLE,F_BUCKET|COPY,F_BUCKET|"7",F_DAYXBUCK
   ITEM "2|2 Settimane" 
-    MESSAGE DISABLE,F_BUCKET|COPY,F_BUCKET
+    MESSAGE SHOW,F_BUCKET|DISABLE,F_BUCKET|COPY,F_BUCKET|"7",F_DAYXBUCK
   ITEM "4|1 Mese" 
-    MESSAGE DISABLE,F_BUCKET|COPY,F_BUCKET
+    MESSAGE SHOW,F_BUCKET|DISABLE,F_BUCKET|COPY,F_BUCKET|"7",F_DAYXBUCK
   ITEM "8|2 Mese" 
-    MESSAGE DISABLE,F_BUCKET|COPY,F_BUCKET
+    MESSAGE SHOW,F_BUCKET|DISABLE,F_BUCKET|COPY,F_BUCKET|"7",F_DAYXBUCK
   ITEM "13|3 Mesi" 
-    MESSAGE DISABLE,F_BUCKET|COPY,F_BUCKET
+    MESSAGE SHOW,F_BUCKET|DISABLE,F_BUCKET|COPY,F_BUCKET|"7",F_DAYXBUCK
   ITEM "17|4 Mesi" 
-    MESSAGE DISABLE,F_BUCKET|COPY,F_BUCKET
+    MESSAGE SHOW,F_BUCKET|DISABLE,F_BUCKET|COPY,F_BUCKET|"7",F_DAYXBUCK
   ITEM "26|6 Mesi" 
-    MESSAGE DISABLE,F_BUCKET|COPY,F_BUCKET
+    MESSAGE SHOW,F_BUCKET|DISABLE,F_BUCKET|COPY,F_BUCKET|"7",F_DAYXBUCK
   ITEM "52|1 Anno" 
-    MESSAGE DISABLE,F_BUCKET|COPY,F_BUCKET
-  ITEM " |Personalizzato"
-    MESSAGE ENABLE,F_BUCKET
+    MESSAGE SHOW,F_BUCKET|DISABLE,F_BUCKET|COPY,F_BUCKET|"7",F_DAYXBUCK
+ ITEM " |Personalizzato"
+    MESSAGE ENABLE,F_BUCKET|"7",F_DAYXBUCK
+  ITEM "G|1 Giorno" 
+    MESSAGE HIDE,F_BUCKET|"1",F_BUCKET|"1",F_DAYXBUCK
+  ITEM "M|Mese solare" 
+    MESSAGE HIDE,F_BUCKET|"31",F_BUCKET|"1",F_DAYXBUCK
 END
 
 NUMBER F_BUCKET 2
@@ -80,6 +84,14 @@ BEGIN
   CHECKTYPE REQUIRED
 END
 
+LIST F_DAYXBUCK 1 9
+BEGIN
+  PROMPT 65 4  ""
+  ITEM "7|settimane"
+  ITEM "1|giorni"
+  FLAGS "D"
+END
+
 LIST F_RAGGRUM 1 53
 BEGIN
   PROMPT 2 5 "Raggruppa        "
@@ -258,6 +270,12 @@ BEGIN
   GROUP 6 7
 END 
 
+STRING F_REPORT 70 50
+BEGIN
+	PROMPT 1 19 "Report "
+	RSELECT "mr1100"
+	GROUP 1
+END
 ENDPAGE
 
 PAGE "Selezione"  -1 -1 78 20
diff --git a/mr/mr1100b.frm b/mr/mr1100b.frm
index 55fae89f0..643f10d55 100755
--- a/mr/mr1100b.frm
+++ b/mr/mr1100b.frm
@@ -2,7 +2,7 @@
 // e la stampa scheduling del bucket suddiviso per linee
 
 
-USE 132 KEY 2
+USE LF_MRPREPORT KEY 1
 JOIN LF_ANAMAG INTO CODART==CODART
 JOIN IMP ALIAS 201 INTO CODTAB==IMPIANTO
 JOIN LNP ALIAS 202 INTO CODTAB==LINEA
@@ -51,7 +51,7 @@ END //HEADER
 
 SECTION BODY ODD 3 COLUMNWISE
 
-STRING 1 50
+STRING 1 50 2
 BEGIN
  SPECIAL STRINGA INTESTAZIONE "Impianto" "Impianto"
  SPECIAL NUMERO OFFSET "0" "Offset iniziale campo"
@@ -61,7 +61,7 @@ BEGIN
  MESSAGE _STREXPR,IMPIANTO+ " "+201@->S0|RESET,1@
 END
 
-STRING 2 4
+STRING 2 2
 BEGIN
  SPECIAL STRINGA INTESTAZIONE "UM" "UM"
  SPECIAL NUMERO OFFSET "0" "Offset iniziale campo"
@@ -198,7 +198,7 @@ SECTION IMPIANTI 2 0 4 FILE 132 GROUP IMPIANTO
   
   SECTION LINEE 2 0 3 FILE 132 GROUP LINEA
    FLAGS "H"
-    STRINGA 300 50
+    STRINGA 300 50 2
     BEGIN
       PROMPT 1 1 "  Articolo "
       MESSAGE _STREXPR,CODART+ " "+LF_ANAMAG->DESCR|RESET,3@
@@ -221,7 +221,7 @@ SECTION IMPIANTI 2 0 4 FILE 132 GROUP IMPIANTO
           PROMPT 1 1 ""
         END
         
-        STRINGA 502 4
+        STRINGA 502 2
         BEGIN
           KEY "UM"
           PROMPT 2 1 ""
@@ -519,7 +519,7 @@ SECTION IMPIANTI 2 0 4 FILE 132 GROUP IMPIANTO
         PROMPT 1 2 "   Totale livello giacenza "
       END
       
-      STRINGA 402 4
+      STRINGA 402 2
       BEGIN
         KEY "UM"
         PROMPT 2 2 ""
@@ -638,7 +638,7 @@ SECTION IMPIANTI 2 0 4 FILE 132 GROUP IMPIANTO
       PROMPT 1 2 "  Totale articolo "
     END
     
-    STRINGA 302 4
+    STRINGA 302 2
     BEGIN
       KEY "UM"
       PROMPT 2 2 ""
@@ -757,7 +757,7 @@ SECTION IMPIANTI 2 0 4 FILE 132 GROUP IMPIANTO
     PROMPT 1 2 " Totale linea "
   END
   
-  STRINGA 202 4
+  STRINGA 202 2
   BEGIN
     KEY "UM"
     PROMPT 2 2 ""
@@ -1051,7 +1051,7 @@ SECTION IMPIANTI 2 0 4 FILE 132 GROUP IMPIANTO
     PROMPT 1 3 " Carico linea"
   END
   
-  STRINGA 239 10
+  STRINGA 239 8
   BEGIN
     KEY "UM"
     FLAGS "H"
@@ -1166,7 +1166,7 @@ BEGIN
  PROMPT 1 2 "Totale impianto"
 END
 
-STRING 102 4
+STRING 102 2
 BEGIN
  SPECIAL STRINGA FINCATURA "XX" "Fincatura sinistra e destra"
  KEY "UM"
diff --git a/mr/mr2100.cpp b/mr/mr2100.cpp
index 9688dd595..1f137ef91 100755
--- a/mr/mr2100.cpp
+++ b/mr/mr2100.cpp
@@ -311,10 +311,11 @@ const TMRP_time& TMRP_line::lead_time(int i, TMRP_time& t, bool anticipate) cons
 
   if (anticipate)
   {
-    if (!cache().get(LF_DIST, articolo()).empty())
+    const TRectype& dist = cache().get(LF_DIST, articolo());
+    if (!dist.empty())
     {
-      int days = cache().get(LF_DIST, articolo()).get_int("LEADTIME");
-      long hours = cache().get(LF_DIST, articolo()).get_long("LEADHOURS");
+      const int days = dist.get_int("LEADTIME");
+      const long hours = dist.get_long("LEADHOURS");
       t.sub_time(days, hours);
     }
     else
@@ -498,7 +499,7 @@ public:
   TRiga_ordine& operator=(TToken_string& r);
   TRiga_ordine& operator+=(TRiga_ordine& r);
 
-  TRiga_ordine() : TToken_string(128) { }
+//  TRiga_ordine() : TToken_string(128) { CHECK(0, "Miiii"): }
   TRiga_ordine(const TDate& datadoc, const TDate& datacons, long forn, 
                const TMRP_line& line, int bucket, const real & price);
   virtual ~TRiga_ordine() { }
@@ -917,6 +918,7 @@ protected:
   
   bool ask_save();
   void save_orders(TAssoc_array& docs);
+  long compute_production_time(const TMRP_line& line, const real& qta) const;
 
 public:
   virtual bool menu(MENU_TAG mt);
@@ -1287,7 +1289,8 @@ int TMatResMask::add_order_line(long forn, const TMRP_line& line, int bucket)
         r->add(pl_orders->get_ref(nref).datacons().string() , F_DATACONS - FIRST_FIELD);
         r->add(pl_orders->get_ref(nref).datadoc().string(), F_DATADOC - FIRST_FIELD);
         q = ZERO;
-      } else
+      } 
+      else
         r->add(" " , F_QUANTITA - FIRST_FIELD);
     } 
     else 
@@ -1712,7 +1715,7 @@ bool TRisalita_mask::on_field_event(TOperable_field& o, TField_event e, long jol
 int TRisalita_mask::add_internal_ref(const TMRP_internalref &iref)
 {
   const TMRP_line& line=*iref.line();
-  int bucket=iref.bucket();
+  int bucket=iref.bucket(); 
 
   const TMRP_time &deliv_time = line.time(bucket);
   TMRP_time doc_time;
@@ -1763,6 +1766,11 @@ int TRisalita_mask::add_internal_ref(const TMRP_internalref &iref)
       r.add(docref->numrig() , F_DOCNRIGA - FIRST_FIELD);
       r.add(qtaplan.string() , F_QUANTITA - FIRST_FIELD);
       um = docref->um();
+
+      const TRectype& rdoc = docref->get_rdoc();
+      r.add(rdoc.get(RDOC_DAANNO), F_DAANNO - FIRST_FIELD);
+      r.add(rdoc.get(RDOC_DACODNUM), F_DACODNUM - FIRST_FIELD);
+      r.add(rdoc.get(RDOC_DANDOC), F_DANUMDOC - FIRST_FIELD);
     } 
     else
     {
@@ -1927,6 +1935,10 @@ bool TMatResPlanning::load_gross_requirements()
 
   // Scandisce tutte le numerazioni considerando solo quelle
   // contenenti i tipi documento specificati nella maschera
+
+  // Inizializza la cache delle lavorazioni
+
+  _artinfo.init(m.get_bool(F_KEEP_IMP)); 
   for (int err = cod.first(num); err == NOERR; err = cod.next(num))
   {
     pi.addstatus(1);
@@ -1985,9 +1997,9 @@ bool TMatResPlanning::load_gross_requirements()
               {
                 const TCodice_articolo art = riga.get(RDOC_CODARTMAG);
                 const TString16 liv = riga.get(RDOC_LIVELLO); 
-                const TString8 mag = nomag ? EMPTY_STRING : riga.get(RDOC_CODMAG).left(nodep ? 3 : 5); 
-                const TString8 imp = noimp ? EMPTY_STRING : riga.get(RDOC_IMPIANTO); 
-                const TString8 lin = nolin ? EMPTY_STRING : riga.get(RDOC_LINEA); 
+                TString8 mag = nomag ? EMPTY_STRING : riga.get(RDOC_CODMAG).left(nodep ? 3 : 5); 
+                TString8 imp = noimp ? EMPTY_STRING : riga.get(RDOC_IMPIANTO); 
+                TString8 lin = nolin ? EMPTY_STRING : riga.get(RDOC_LINEA); 
                 const TCodice_um um = riga.get(RDOC_UMQTA);
 
                 // GUY was Here, but it's Koki fault!
@@ -1997,11 +2009,14 @@ bool TMatResPlanning::load_gross_requirements()
                 TQuantita q(art, um, qta);
                 q.convert2umbase();
                 q.currency2umbase(prz);
-                TMRP_line* line = _articles.find(art, liv, mag, "", imp, lin, codcli);
+							
+								if (lin.empty())
+									_artinfo.art2magimpline(art, mag, imp, lin);
+                TMRP_line* line = _articles.find(art, liv, mag, EMPTY_STRING, imp, lin, codcli);
                 if (line == NULL)
                 {
                   // nuova linea
-                  line = _articles.find(art, liv, mag, "", imp, lin, codcli, true);
+                  line = _articles.find(art, liv, mag, EMPTY_STRING, imp, lin, codcli, true);
                   line->set_description(riga.get(RDOC_DESCR));
                   line->set_final_product();
                 }
@@ -2011,7 +2026,13 @@ bool TMatResPlanning::load_gross_requirements()
                 TMRP_docref * docref = new TMRP_docref(doc.get_int(DOC_ANNO), codnum, docnum,
                             numriga, um, qta, prz.get_num());
 
-                const TMRP_time t(datacons, 0, imp, lin);
+                TMRP_time t(datacons, 0, imp, lin);
+                if (m.get_int(F_LDTIME_MODE) != 0)
+                {
+                  t.add_time(0, -1); // Toglie un'ora: sposta datacons a fine turno
+                  t.add_time(0, +1); // Riaggiunge un'ora nel giorno stesso
+                }
+
                 line->add_gross_req(t, q.val(), docref);
                 if (master)
                   line->add_net_req(t, q.val());
@@ -2034,12 +2055,13 @@ bool TMatResPlanning::explode_articles()
   const TMatResMask& m = *_mask;
   TDistinta_tree distinta; // albero distinta
   TArray boom;             // array per i figli
-  int level = 1;
+  int level = 0;
+	int maxlevel = m.get_int(F_MAXLEVEL);
   bool finiti = TRUE;
   TProgind* pi = NULL;
 
   // Inizializza la cache delle lavorazioni
-  _artinfo.init(m.get_bool(F_KEEP_IMP)); 
+//  _artinfo.init(m.get_bool(F_KEEP_IMP)); ??
   
   // Scandisce gli articoli inseriti dal gross requirements ed 
   // accoda tutti gli articoli risultanti dalla loro esplosione
@@ -2053,8 +2075,10 @@ bool TMatResPlanning::explode_articles()
     }
     if (pi == NULL)
     {
+			if (maxlevel > 0 && level >= maxlevel)
+				return _articles.items() > 0;
       TString80 msg;
-      msg.format(FR("Esplosione articoli (livello %d)"), level++);
+      msg.format(FR("Esplosione articoli (livello %d)"), ++level);
       pi = new TProgind(_articles.items()-a, msg, TRUE, TRUE);
     }
     pi->addstatus(1);
@@ -2139,6 +2163,8 @@ bool TMatResPlanning::load_planned_orders()
   const int year_fr = date_fr.year() - (m.get_bool(F_DOC_YEAR_PREC) ? 1 : 0);
   const int year_to = date_to.year();
 
+	const bool load_evasi = m.get_bool(F_LOAD_EVASI);
+
   TTable num("%NUM");
   TCodice_numerazione cod;
 
@@ -2181,7 +2207,7 @@ bool TMatResPlanning::load_planned_orders()
       // quelli con uno stato nel range corretto
       for (cur = 0; cur.pos() < items; ++cur)    
       {
-        const bool evaso = curr.get_bool(DOC_DOCEVASO);
+        const bool evaso = !load_evasi && curr.get_bool(DOC_DOCEVASO);
         if (evaso)
           continue;
 
@@ -2212,7 +2238,7 @@ bool TMatResPlanning::load_planned_orders()
 
           if (riga.is_articolo())
           {
-            const real qta = riga.qtaresidua();
+            const real qta = load_evasi ? riga.quantita() : riga.qtaresidua();
             if (qta > ZERO)
             {
               const TCodice_articolo art = riga.get(RDOC_CODARTMAG);
@@ -2224,10 +2250,10 @@ bool TMatResPlanning::load_planned_orders()
               // GUY was Here, but it's Koki fault!
               const long codcli = is_production_article(art) ? doc.get_long(DOC_CODCF) : 0;
 
-              TMRP_line* line = _articles.find(art, liv, mag, "", imp, lin, codcli);
+              TMRP_line* line = _articles.find(art, liv, mag, EMPTY_STRING, imp, lin, codcli);
               if (line == NULL)
               {
-                line = _articles.find(art, liv, mag, "", imp, lin, codcli, TRUE);
+                line = _articles.find(art, liv, mag, EMPTY_STRING, imp, lin, codcli, TRUE);
                 line->set_description(riga.get(RDOC_DESCR));
               }
               TPrice prz(riga.prezzo(TRUE,TRUE));
@@ -2266,7 +2292,7 @@ bool TMatResPlanning::preprocess_cycle()
   // costruisce gli sched rec degli elementi dai DOCS ordini fornitore emessi
   ok |= load_planned_orders();
   if (ok)
-    // esplode l'array mediante la DIBA
+    // esplode l'array mediante la Distinta Base
     return explode_articles();
 
 /*
@@ -2277,7 +2303,38 @@ bool TMatResPlanning::preprocess_cycle()
       // costruisce gli sched rec degli elementi dai DOCS ordini fornitore emessi
       return load_planned_orders(m);
 */
-  return FALSE;
+  return false;
+}
+
+long TMatResPlanning::compute_production_time(const TMRP_line& line, const real& qta) const
+{
+  real tot;
+  if (line.codlin().not_empty())
+  {
+    TDistinta_tree tree;
+  
+    tree.set_global("_MAGDEP", line.codmagdep());
+    tree.set_global("_LINEA", line.codlin());
+    tree.set_global("_IMPIANTO", line.codimp());
+    tree.set_root(line.articolo(), "", qta, line.livgiac());
+
+    TArray lav_array;        
+    for (TRiga_esplosione* llav = tree.first_labor(lav_array, RAGGR_EXP_UMBASE); llav; 
+         llav = tree.next_labor(lav_array))
+    {
+      TLavorazione* lavorazione = tree.find_labor(llav);
+      const int linea = lavorazione->find_linea(line.codlin());
+      if (linea >= 0)
+      {
+        const real prod_linea = lavorazione->produttiv_linea(linea);
+        real ore = (llav->val() * lavorazione->um_temporale().converti_in_ore()) / prod_linea;
+        // if (carico_uomo) ore *= lavorazione->numpers_linea(linea); 
+        tot += ore;
+      } 
+    }
+    tot.ceil();
+  }
+  return tot.integer();
 }
 
 /////////// finished: 99%
@@ -2333,16 +2390,33 @@ bool TMatResPlanning::gross2net_logic(TMRP_line &curr_article, int bucket, bool
   // trasforma i fabbisogni totali nel fabbisogno lordo dei figli
   net_req += curr_article.sched_receipts(bucket);
   // net_req += curr_article.planned_orders(bucket);//planned orders are not added here, but in build orders phase
-  if (net_req > ZERO && n_figli)
+  if (net_req > ZERO && n_figli > 0)
   {
-    TMRP_time lead_time, xlead_time; 
+    TMRP_time lead_time; 
     curr_article.lead_time(bucket, lead_time, use_leadtime);
+    
+    const int ldtime_mode = m.get_int(F_LDTIME_MODE);
+    if (ldtime_mode == 1 || ldtime_mode == 2)
+    {
+      const long xtrahours = compute_production_time(curr_article, net_req);
+      if (xtrahours > 0)
+      {
+        if (ldtime_mode == 1)
+          lead_time.sub_time(0, xtrahours);
+        else
+        {
+          TMRP_time prod_time = curr_article.time(bucket);
+          prod_time.sub_time(0, xtrahours);
+          if (prod_time < lead_time)
+            lead_time = prod_time;
+        }
+      }
+    }
+
     const int xtradays = m.get_int(F_XTRA_LDTIME);
     if (xtradays)
-    {
-      xlead_time = lead_time;
-      xlead_time.sub_time(xtradays);
-    }
+      lead_time.sub_time(xtradays);
+
     for (int o = 0; o < n_figli; o++)
     {
       TMRP_line& article_son = curr_article.son(o);
@@ -2351,14 +2425,11 @@ bool TMatResPlanning::gross2net_logic(TMRP_line &curr_article, int bucket, bool
       if (tmpreal > ZERO) 
       {
         TMRP_internalref * iref = new TMRP_internalref( &curr_article, bucket, tmpreal);
-        if (xtradays && curr_article.sons())
-          article_son.add_gross_req(xlead_time, tmpreal, iref);
-        else
-          article_son.add_gross_req(lead_time, tmpreal, iref);
+        article_son.add_gross_req(lead_time, tmpreal, iref);
       }
     }
   }
-  return TRUE;
+  return true;
 }
 
 /////////// finished: 99%
@@ -2367,7 +2438,7 @@ bool TMatResPlanning::net_requirement_cycle()
 {
   const TMatResMask& m = *_mask;
 
-  bool ok = TRUE;
+  bool ok = true;
   // ordina gli articoli
   const long total = _articles.sort();
 
@@ -2385,7 +2456,7 @@ bool TMatResPlanning::net_requirement_cycle()
     {
       real curgiac;
       curr_article.set_on_hand(0, curr_article.giacenza_attuale(curgiac, m.get_date(F_DADATA)));
-      bool sc_used = FALSE;
+      bool sc_used = false;
       
       for (int bucket = 0; ok && bucket <= last; bucket = curr_article.next_bucket(bucket))
       {
@@ -2675,15 +2746,21 @@ TMRP_line* TMatResPlanning::find_risalita_line(TToken_string &row)
   long codcf = row.get_long(sf.cid2index(F_FORNITORE));
     
   TMRP_line* line = _articles.find(art, liv, mag, magc, imp, lin, codcf);
-  if (line == NULL)
-  {
-    line = _articles.find(art, liv, mag, magc, imp, lin, 0L); // Riprovo senza clifo
-    if (line == NULL)
-    {
-      line = _articles.find(art, liv, mag, magc, imp, EMPTY_STRING, codcf);  // Riprovo senza linea
-      if (line == NULL)
-        line = _articles.find(art, liv, mag, magc, imp, EMPTY_STRING, 0L);     // Riprovo senza nulla
-    }
+	if (line == NULL)
+	{
+		line = _articles.find(art, liv, mag, magc, imp, lin, 0L); // Riprovo senza clifo
+		if (line == NULL)
+		{
+			line = _articles.find(art, liv, mag, magc, imp, EMPTY_STRING, codcf);  // Riprovo senza linea
+			if (line == NULL)
+			{
+				line = _articles.find(art, liv, mag, magc, EMPTY_STRING, lin, codcf);  // Riprovo senza impianto
+				if (line == NULL)
+				{
+					line = _articles.find(art, liv, mag, magc, imp, EMPTY_STRING, 0L);     // Riprovo senza nulla
+				}
+			}
+		}
   }
 
   return line;
@@ -2734,7 +2811,7 @@ bool TMatResPlanning::print_risalita(const TMRP_line & line, const TDate &date,
         plan  += line.planned_orders(b);
         sched += line.sched_receipts(b);
         TMRP_internalrefs *irefs = line.record(b).internal_refs();
-        if (irefs)
+        if (irefs != NULL)
         {
           int ir = 0;
           while (ir < irefs->items())
@@ -2926,13 +3003,26 @@ void TMatResPlanning::save_orders(TAssoc_array& docs)
     if (doc.get_long(DOC_NDOC))
     {
       // riscrittura; elimina righe con qta zero
-      if (!m.get_bool(F_ALL_ORDERSCHANGES))
-        for (int numriga = doc.physical_rows(); numriga >0 ; numriga--)
-        {
-          if (doc[numriga].get_real(RDOC_QTA).is_zero())
-            doc.destroy_row(numriga, TRUE);
-        }
-      err = doc.rewrite();
+//      if (!m.get_bool(F_ALL_ORDERSCHANGES))
+			int nrows = doc.physical_rows();
+
+			for (int numriga = nrows; numriga >0 ; numriga--)
+			{
+				if (doc[numriga].get_real(RDOC_QTA).is_zero())
+					doc.destroy_row(numriga, TRUE);
+			}
+			
+			nrows = doc.physical_rows();
+			
+			if (nrows > 0)
+	      err = doc.rewrite();
+			else
+			{
+				TDocumento d;
+				
+				if (d.read(doc, _isequal, _testandlock) == NOERR)
+					d.remove();
+			}
     }
     else
       // generazione
@@ -2989,12 +3079,15 @@ const TRectype* TMatResPlanning::irefs2rdoc(const TMRP_internalrefs& irefs) cons
         {
           const TMRP_docref& docref = *refs->get_ref_ptr(j);
           if (docref.numrig() > 0)
+          {
             rdoc = &docref.get_rdoc();
+            break;
+          }
         }
       }
     }
 
-    // Quin comincia la magia, perche' differente dalla risalita standard
+    // Qui comincia la magia, perche' differente dalla risalita standard
     if (rdoc == NULL)
     {
       const TMRP_internalrefs* inter = rec.internal_refs();
@@ -3142,7 +3235,7 @@ bool TMatResPlanning::emit_orders()
         rdoc.put(RDOC_CODART, riga.get(sf.cid2index(F_ARTICOLO)));
       
         TString80 str;
-        for (int l= livelli_giacenza().last_level(); l>=1; l--)
+        for (int l= livelli_giacenza().last_level(); l>0; l--)
           livelli_giacenza().pack_grpcode(str, riga.get(sf.cid2index(F_LIV1+l-1)), l);
         rdoc.put(RDOC_LIVELLO,str);
       
@@ -3175,37 +3268,60 @@ bool TMatResPlanning::emit_orders()
         riga.add("X",sf.cid2index(F_OK));
 
         // Cerca di impostare la riga di provenienza dell'ordine
-        if (rdoc.get(RDOC_DAPROVV).blank())                 // Se e' una riga nuova...
+        if (rdoc.get(RDOC_DAPROVV).blank())              // Se e' una riga nuova ...
         {
-          TMRP_line* line = find_risalita_line(riga);       // ... cerco la riga di risalita
+          TMRP_line* line = find_risalita_line(riga);    // ... cerco la riga di risalita
           if (line != NULL)
           {
             const int depth = line->explosion_depth()+1; // Profondita' esplosione (+1 per non avere zeri)
             rdoc.put(RDOC_QTAGG5, depth);                // Per ora memorizziamo in QTAGG5, scelto a caso
 
             // Cerco la riga di risalita
-            for (int bucket = line->last_bucket(); bucket >= 0; bucket--)
+						const TRectype* dardoc = NULL;
+						int bucket;
+						const int last_bucket = line->last_bucket();
+
+						for (bucket = last_bucket; bucket >= 0; bucket--)
+						{
+							if (datacon >= line->record(bucket).time().date())
+							{
+								TMRP_internalrefs *irefs = line->record(bucket).internal_refs();
+								if (irefs != NULL && irefs->items() > 0)
+									dardoc = irefs2rdoc(*irefs);
+								if (dardoc == NULL)
+								{
+									TMRP_docrefs* gr_refs = line->record(bucket).requirements_refs();
+									if (gr_refs != NULL && gr_refs->items() > 0)  // Esiste almeno una riga di risalita     
+									{
+										const TMRP_docref& docref = *gr_refs->get_ref_ptr(0);
+										dardoc = &docref.get_rdoc();
+                    break;
+									}
+								}
+								else
+									break;
+							}
+						}
+						if (dardoc != NULL)
+						{
+							int depth = m.get_int(F_RIFERIMENTO_MRP);
+							if (depth == 0 && dardoc->get(RDOC_DACODNUM).not_empty())
+								depth = 1;
+							rdoc.set_original_rdoc_key(*dardoc, depth);          // Imposto DAPROVV, DAANNO, DACODNUM, DANDOC, DAIDRIGA
+						}
+						else 
             {
-              const TRectype* dardoc = NULL;
-              TMRP_internalrefs *irefs = line->record(bucket).internal_refs();
-              if (irefs != NULL && irefs->items() > 0)
-                dardoc = irefs2rdoc(*irefs);
-              if (dardoc == NULL)
-              {
-                TMRP_docrefs* gr_refs = line->record(bucket).requirements_refs();
-                if (gr_refs != NULL && gr_refs->items() > 0)  // Esiste almeno una riga di risalita     
-                {
-                  const TMRP_docref& docref = *gr_refs->get_ref_ptr(0);
-                  dardoc = &docref.get_rdoc();
-                }
-              }
-              if (dardoc != NULL)
-              {
-                rdoc.set_original_rdoc_key(*dardoc);          // Imposto DAPROVV, DAANNO, DACODNUM, DANDOC, DAIDRIGA
-                break;
-              }
+              TString80 msg; msg.format(FR("Riferimento non trovato: riga %d"), r+1);
+							xvt_statbar_set(msg);
+              beep();
             }
           }
+          else
+          {
+            TString80 msg; msg.format(FR("Linea risalita non trovata: riga %d"), r+1);
+  					xvt_statbar_set(msg);
+            beep();
+          }
         }
       } 
     }
diff --git a/mr/mr2100.h b/mr/mr2100.h
index e3ff76589..f562a09d7 100755
--- a/mr/mr2100.h
+++ b/mr/mr2100.h
@@ -1,6 +1,9 @@
 #ifndef __MR2100_H
 #define __MR2100_H
 
+#include "mrplib.h"
+#include "../ve/velib.h"
+
 void print_header(TPrinter& pr);
 void print_footer(TPrinter& pr);
 
diff --git a/mr/mr2100a.h b/mr/mr2100a.h
index 9a29052fc..9eac0706f 100755
--- a/mr/mr2100a.h
+++ b/mr/mr2100a.h
@@ -50,10 +50,14 @@
 #define F_DAYXBUCK      244
 #define F_XTRA_LDTIME  245
 #define F_XTRA_PLTIME  246
+#define F_LDTIME_MODE 247
 #define F_ALL_ORDERSCHANGES  250
 #define F_DISABLESAVE 251
 #define F_ALL_MRPLINES  252
 #define F_DOC_YEAR_PREC 253
+#define F_MAXLEVEL    254
+#define F_RIFERIMENTO_MRP 255
+#define F_LOAD_EVASI 256
 
 // campi senza default sul profilo
 #define F_YEAR        301
@@ -102,8 +106,10 @@
 #define F_DOCCODNUM   120 // 2
 #define F_DOCNUM      121 // 3
 #define F_DOCNRIGA    122 // 4
-
-#define F_OK          123
+#define F_DAANNO      123 // lasciare questi 3 campi in sequenza
+#define F_DACODNUM    124 // 
+#define F_DANUMDOC    125 // 
+#define F_OK          126
 
 #define F_RAGSOC      154
 #define F_DESCMAG     160
diff --git a/mr/mr2100a.uml b/mr/mr2100a.uml
index f35a00c88..d26fa5061 100755
--- a/mr/mr2100a.uml
+++ b/mr/mr2100a.uml
@@ -184,14 +184,14 @@ BEGIN
   PROMPT 1 10 "@bOrdini produzione/fornitori"
 END
 
-SPREADSHEET F_NUM_ORF 8
+SPREADSHEET F_NUM_ORF 8 9
 BEGIN
   GROUP G_PREPROCESS
   PROMPT 1 11 ""
   ITEM "Codice"
 END
 
-SPREADSHEET F_TIPI_ORF 62 
+SPREADSHEET F_TIPI_ORF 62 9
 BEGIN
   GROUP G_PREPROCESS
   PROMPT 16 11 ""
@@ -202,6 +202,11 @@ BEGIN
   ITEM "Stato def."
 END
 
+BOOLEAN F_LOAD_EVASI
+BEGIN
+  PROMPT 2 20 "Non considerare l'evasione ordini"
+END
+
 ENDPAGE
 
 PAGE "Genera"  -1 -1 78 20
@@ -382,6 +387,13 @@ BEGIN
   GROUP G_PREPROCESS
 END
 
+LIST F_RIFERIMENTO_MRP 1 20
+BEGIN
+  PROMPT 2 11 "Riferimento sulle righe "
+  ITEM "0|Documento originale"
+  ITEM "1|Documento padre"
+END
+
 
 
 BOOLEAN F_KEEP_IMP
@@ -410,31 +422,44 @@ BEGIN
   FLAGS "U"
 END
 
+LIST F_LDTIME_MODE 1 50
+BEGIN
+  PROMPT 2 18 "Calcolo lead time "
+  ITEM "0|Normale"
+  ITEM "1|Sommare al lead time il tempo di produzione"
+  ITEM "2|Massimo tra lead time e tempo di produzione"
+END
+
+NUMBER F_MAXLEVEL 3
+BEGIN
+  PROMPT 2 19 "Max.livello di esplosione "
+  FLAGS "U"
+END
+
 NUMBER F_XTRA_LDTIME 2
 BEGIN
   GROUP G_PREPROCESS
-  PROMPT 2 18 "Anticipa le consegne di  "
+  PROMPT 2 20 "Anticipa le consegne di   "
   FLAGS "U"
 END
 
 TEXT DLG_NULL
 BEGIN
   GROUP G_PREPROCESS
-  PROMPT 31 18 "giorni lavorativi"
-  FLAGS "U"
+  PROMPT 32 20 "giorni lavorativi"
 END
 
 NUMBER F_XTRA_PLTIME 2
 BEGIN
   GROUP G_PREPROCESS
-  PROMPT 2 19 "Anticipa le emissioni di "
+  PROMPT 2 21 "Anticipa le emissioni di  "
   FLAGS "U"
 END
 
 TEXT DLG_NULL
 BEGIN
   GROUP G_PREPROCESS
-  PROMPT 31 19 "giorni lavorativi"
+  PROMPT 32 21 "giorni lavorativi"
   FLAGS "U"
 END
 
diff --git a/mr/mr2100b.uml b/mr/mr2100b.uml
index a422e4b46..0ae5c4692 100755
--- a/mr/mr2100b.uml
+++ b/mr/mr2100b.uml
@@ -160,6 +160,9 @@ BEGIN
   ITEM "Cod.Num."
   ITEM "Num.Doc."
   ITEM "Num.Riga."
+  ITEM "Da Anno"
+  ITEM "Da Cod.Num."
+  ITEM "Da Num.Doc."
 END
 
 BUTTON DLG_CANCEL 10 2
@@ -432,6 +435,22 @@ BEGIN
   FLAGS "H"
 END
 
+STRING F_DAANNO  4
+BEGIN
+  PROMPT 1 14 "Da Anno     "
+END
+
+STRING F_DACODNUM   4
+BEGIN
+  PROMPT 19 14 "Documento "
+END
+
+NUMBER F_DANUMDOC      9
+BEGIN
+  PROMPT 35 14 "N. "
+END
+
+
 
 BUTTON DLG_OK 10 2
 BEGIN
diff --git a/mr/mr2200.cpp b/mr/mr2200.cpp
index 4b4927222..ed96c6da5 100755
--- a/mr/mr2200.cpp
+++ b/mr/mr2200.cpp
@@ -1,7 +1,13 @@
 #include "mr2200.h"
 #include "mr2200a.h"
 #include "mr2200b.h"
-#include <cfven.h>
+
+#include <defmask.h>
+#include <progind.h>
+#include <tabutil.h>
+#include <utility.h>
+
+#include "../ve/veconf.h"
 
 class TMSPCheck_mask : public TAutomask
 {
@@ -10,12 +16,12 @@ protected:
   TPlanning_mask * _main_mask;
   TSheet_field * _sheet;
 protected:
-  int max_rows() {return _sheet->items();}
+  int max_rows() const { return _sheet->items(); }
   void go_top();
   bool on_field_event(TOperable_field& o, TField_event e, long jolly);
   bool move_to(int dlg);
   virtual void check_pos_range();
-  virtual int fill_mask(const bool show=TRUE);
+  virtual int fill_mask(const bool show=true);
   virtual bool is_constraint(int row);
   virtual bool is_article(int row);
   virtual int find_constr_row(int row);
@@ -35,7 +41,7 @@ class TCRPCheck_mask : public TMSPCheck_mask
 {
 protected:
   virtual void check_pos_range();
-  virtual int fill_mask(const bool show=TRUE);
+  virtual int fill_mask(const bool show=true);
   virtual bool is_constraint(int row);
   virtual bool is_article(int row);
   virtual int find_constr_row(int row);
@@ -129,7 +135,7 @@ bool TPlann_sub_mask::on_field_event(TOperable_field& o, TField_event e, long jo
       save_profile();
       break;
   }
-  return TRUE;
+  return true;
 }
 ///////////////////////////////////////////////////////////
 // Maschera stampa
@@ -174,7 +180,7 @@ bool TPrint_mask::on_field_event(TOperable_field& o, TField_event e, long jolly)
           case 'E':
           {
             TExceptions_array e;
-            if (_m->find_exceptions(e, get_bool(S_HURRYUP_EXCEPT),get_bool(S_DELAY_EXCEPT),get_bool(S_EXTRA_EXCEPT), get_bool(S_STOCKBRK_EXCEPT), get_bool(S_CODEMISS_EXCEPT), TRUE))
+            if (_m->find_exceptions(e, get_bool(S_HURRYUP_EXCEPT),get_bool(S_DELAY_EXCEPT),get_bool(S_EXTRA_EXCEPT), get_bool(S_STOCKBRK_EXCEPT), get_bool(S_CODEMISS_EXCEPT), true))
               _m->print_exceptions(e); 
           }
           break;
@@ -183,7 +189,7 @@ bool TPrint_mask::on_field_event(TOperable_field& o, TField_event e, long jolly)
     default:
       TPlann_sub_mask::on_field_event(o,e,jolly);
   }
-  return TRUE;
+  return true;
 }
 
 ///////////////////////////////////////////////////////////
@@ -203,10 +209,10 @@ bool TSave_mask::on_field_event(TOperable_field& o, TField_event e, long jolly)
   {
     case F_SAVE_OPT:
       if (e == se_query_add)
-        return FALSE;
+        return false;
       break;
     case DLG_QUIT:
-      _m->find_exceptions(_exceptions, TRUE,TRUE,TRUE,FALSE,TRUE);
+      _m->find_exceptions(_exceptions, true,true,true,false,true);
       if (_m->salva_documenti(_exceptions, sfield(F_SAVE_OPT))<0)
         _m->elabora(); // necessario per ricaricare i rif alle righe
       if (_exceptions.items())
@@ -220,7 +226,7 @@ bool TSave_mask::on_field_event(TOperable_field& o, TField_event e, long jolly)
     default:
       TPlann_sub_mask::on_field_event(o,e,jolly);
   }
-  return TRUE;
+  return true;
 }
 
 ///////////////////////////////////////////////////////////
@@ -375,7 +381,7 @@ bool TPlanning_mask::test_tipodoc_num(const  TSheet_field &sheet_num ,const  TSh
   TString_array& types = sheet_type.rows_array();
   for (int j = types.items()-1; j >= 0; j--)
   {
-    bool ok=FALSE;
+    bool ok=false;
     tipo = types.row(j).get(0) ;
     for (int i = nums.items()-1; i >= 0; i--)
     {
@@ -384,13 +390,13 @@ bool TPlanning_mask::test_tipodoc_num(const  TSheet_field &sheet_num ,const  TSh
       {
         const char* t = num.tipo_doc(n);
         if (tipo == t)
-          ok = TRUE;
+          ok = true;
       }
     }
     if (!ok) 
       return error_box(FR("Il tipo '%s' non appartiene a nessuna delle numerazioni scelte"),(const char * )tipo);
   }
-  return TRUE;
+  return true;
 }
 
 int TPlanning_mask::test_status(const TRectype& doc, int s) const
@@ -424,7 +430,7 @@ bool TPlanning_mask::has_confirmed_status(const TRectype &doc, TToken_string &ri
 {
   const char statodoc = doc.get_char(DOC_STATO);
   char def_status = riga.get_char(F_STATODEF-FIRST_FIELD);
-  return def_status > ' ' ? statodoc >= def_status  : FALSE;
+  return def_status > ' ' ? statodoc >= def_status  : false;
 }
 
 bool TPlanning_mask::has_confirmed_status(const TRectype &doc) const
@@ -474,7 +480,7 @@ bool TPlanning_mask::elabora()
     }
     return  some_lines;
   }
-  return FALSE;
+  return false;
 }
 
 bool TPlanning_mask::carica_documenti()
@@ -489,9 +495,9 @@ bool TPlanning_mask::carica_documenti()
 
 
   TDate date_fr(starting_date());
-  const int bucket_fr = round_date(date_fr, FALSE);
+  const int bucket_fr = round_date(date_fr, false);
   TDate date_to = get(F_ADATA);
-  const int bucket_to = round_date(date_to, TRUE);
+  const int bucket_to = round_date(date_to, true);
   const TString80 f_art(get(F_FRART));
   const bool f_art_fill = !f_art.empty();
   TString80 t_art(get(F_TOART));
@@ -502,7 +508,12 @@ bool TPlanning_mask::carica_documenti()
   TString16 t_grm(get(F_TOGRM)); t_grm.rpad(3);
   t_grm << get(F_FRSGM); t_grm.trim();
   const bool t_grm_fill = !t_grm.empty();
-  const bool filtered = f_art_fill || t_art_fill || f_grm_fill || t_grm_fill;
+	TString16 imp; 
+
+	if (!ignore_imp)
+		imp = get(F_IMP);
+
+  const bool filtered = f_art_fill || t_art_fill || f_grm_fill || t_grm_fill || imp.not_empty();
 
   const int year_fr = date_fr.year() - (get_bool(F_DOC_YEAR_PREC) ? 1 : 0);
   const int year_to = date_to.year();
@@ -546,12 +557,12 @@ bool TPlanning_mask::carica_documenti()
       // quelli con uno stato nel range corretto
       TString msg;
       msg.format(FR("Caricamento documenti %s (numerazione '%s')"),tn & _Doc_vincoli ? "ordine":"di planning",(const char *)cod.codice());
-      TProgind pi(items,msg , TRUE, TRUE);
+      TProgind pi(items,msg , true, true);
       for (cur = 0; cur.pos() < items; ++cur)    
       {
         pi.addstatus(1);
         if (pi.iscancelled())
-          return FALSE;
+          return false;
         const bool evaso = curr.get_bool(DOC_DOCEVASO);
         if (evaso)
           continue;
@@ -564,6 +575,10 @@ bool TPlanning_mask::carica_documenti()
         const int sheetrow=test_status(curr, tn);
         if (sheetrow < 0)
           continue;  
+        const bool ignore_prec = get_bool(F_IGNORE_PREC);
+
+        if (ignore_prec && (tn & _Doc_planning) && (datacons < date_fr))
+          continue;
         
         // Scandisce le righe articolo e memorizza
         // le quantita' richieste
@@ -587,6 +602,11 @@ bool TPlanning_mask::carica_documenti()
                 ok = cache().get(LF_ANAMAG, art, ANAMAG_GRMERC) >= f_grm;
               if (ok && t_grm_fill)
                 ok = cache().get(LF_ANAMAG, art, ANAMAG_GRMERC) <= t_grm;
+	            if (ok && imp.not_empty())
+							{
+								const TString & r_imp = riga.get(RDOC_IMPIANTO);
+								ok = (imp == r_imp);
+							}
             }
             if (ok)
             {
@@ -610,15 +630,14 @@ bool TPlanning_mask::carica_documenti()
               if (buck < 0) buck = 0; else
               if (buck > LAST_BUCKET) buck = LAST_BUCKET;
 
-              TMSP_constraint* line;
+              TMSP_constraint* line = NULL;
               if (tn & _Doc_vincoli)
-              {            
-              
-                line = _constraints.find(cli, art, liv, imp, lin, mag, TRUE);
+              {                        
+                line = _constraints.find(cli, art, liv, imp, lin, mag, true);
                 line->set_mastercode_check(two_level && !distinta_master(art));
               }
               else {
-                line = _articles.find(cli, art, liv, imp, lin, mag, magc, TRUE);
+                line = _articles.find(cli, art, liv, imp, lin, mag, magc, true);
               }
 
               if (line->description().empty())
@@ -626,15 +645,61 @@ bool TPlanning_mask::carica_documenti()
 
               if (buck >= 0 && buck <= LAST_BUCKET)
               {
-                int annodoc=riga.get_int(RDOC_ANNO); 
-                TString8 codnum(cod.codice());
+                const int annodoc=riga.get_int(RDOC_ANNO); 
+                TString4 codnum(cod.codice());
                 TString4 tiporiga(riga.get(RDOC_TIPORIGA));
                 char provv= riga.get_char(RDOC_PROVV);
                 long numdoc =  riga.get_long(RDOC_NDOC);
                 int numrig =  riga.get_int(RDOC_NRIGA);
                 real prz =  riga.get_int(RDOC_PREZZO);
                 prz = prz / qta * q.val(); 
-                line->add_rigaref(buck, codnum, annodoc, numdoc, numrig, q.um(), q.val(), prz);// memorizza la provenienza dal doc
+                TMRP_docref* dr = line->add_rigaref(buck, codnum, annodoc, numdoc, numrig, q.um(), q.val(), prz);// memorizza la provenienza dal doc
+
+                const TString& priority_formula = get(F_PRIORITY);
+                if (!priority_formula.blank())
+                {
+                  TExpression expr(priority_formula);
+                  if (expr.numvar() > 0)
+                  {
+                    for (int i = expr.numvar()-1; i >= 0; i--)
+                    {
+                      const TString vn(expr.varname(i));
+											if (vn == "DATE_PRIORITY")
+											{
+                        real buck_priority;
+                        if (tn & _Doc_vincoli)
+                        {
+                          buck_priority = date_to - consegna;
+                          if (buck_priority < ZERO)
+                            buck_priority = ZERO;
+                        }
+												expr.setvar(i, buck_priority);
+											}
+											else
+											{
+												const TFieldref fr(vn, 0);
+												switch (fr.file())
+												{
+												case LF_DOC:
+													expr.setvar(i, fr.read(doc));
+													break;
+												case LF_RIGHEDOC:
+													expr.setvar(i, fr.read(riga));
+													break;
+												default:
+													{
+														const TRectype& recart = cache().get(LF_ANAMAG, art);
+														expr.setvar(i, fr.read(recart));
+													}
+													break;
+												}
+											}
+                    }
+                    const long p = expr.as_real().integer();
+                    if (p > line->priority())
+                      line->priority(p);
+                  }
+                }
               }
               
               if (tn & _Doc_planning)
@@ -644,10 +709,10 @@ bool TPlanning_mask::carica_documenti()
                 const bool confirmed = has_confirmed_status(rel.lfile().curr(), sfield(F_TIPI_PLA).row(sheetrow));
                 if (confirmed)
                 {
-                  //line->qta_locked(buck) = TRUE;
+                  //line->qta_locked(buck) = true;
                   line->qta_min(buck) += q.val();
                 } else {
-                  //add_MRP_bucket(*find_propose(cli, art, liv, imp, lin, mag, magc, TRUE), buck, q.val());
+                  //add_MRP_bucket(*find_propose(cli, art, liv, imp, lin, mag, magc, true), buck, q.val());
                 }
               }
               line->qta(buck) += q.val();
@@ -660,7 +725,7 @@ bool TPlanning_mask::carica_documenti()
           }
         }
       }
-      cur.freeze(FALSE);
+      cur.freeze(false);
     }
   }
 
@@ -737,7 +802,7 @@ TMSP_constraint* TPlanning_mask::find_constraint(const TMSP_line& l, bool force_
   if (c == NULL && force_insert)
   {
     // MA STO VINCOLO MANCA PROPRIO! ALLORA LO INSERISCO 
-    c = _constraints.find(codcli, l.articolo(), l.livgiac(), codimp, codlin, codmag, TRUE);
+    c = _constraints.find(codcli, l.articolo(), l.livgiac(), codimp, codlin, codmag, true);
     if (c->description().blank())
       c->set_description(l.description());
     c->set_mastercode_check(get_bool(F_2LEVEL_MSP) && !distinta_master(l.articolo()));
@@ -852,6 +917,7 @@ void TPlanning_mask::set_sheet_header()
   sf.force_update();
   sl.force_update();
 }
+
 void TPlanning_mask::enable_codes(int row, bool on)
 {
   TSheet_field& sf = sfield(F_ARTICOLI);
@@ -867,6 +933,7 @@ void TPlanning_mask::enable_codes(int row, bool on)
   sf.enable_cell(row,F_MAG_COLL-FIRST_FIELD, on && ignore_mag);
   sf.enable_cell(row,F_DEP_COLL-FIRST_FIELD, on && ignore_mag);
 }
+
 void TPlanning_mask::fill_sheet()
 {
   set_sheet_header();
@@ -882,7 +949,7 @@ void TPlanning_mask::fill_sheet()
   for (long i = 0; i < totart; i++)
   {
     TMSP_line& line = _articles[i];
-    TMSP_constraint* curr_constraint = find_constraint(line,TRUE);
+    TMSP_constraint* curr_constraint = find_constraint(line,true);
     int new_row = -1;
     
     for (int nrow = int (sf.items()) - 1; nrow >=0; nrow--)
@@ -983,8 +1050,8 @@ int TPlanning_mask::insert_propose(bool verbose)
 }
 bool TPlanning_mask::remove_propose(bool verbose) 
 {
-  bool remove = FALSE;
-  bool remove_all = FALSE;
+  bool remove = false;
+  bool remove_all = false;
   bool some = _proposed_articles.items() > 0L; // proposte attuali
   if (some)
     remove = (!verbose || yesno_box(TR("Vuoi annullare le nuove proposte?")));
@@ -997,7 +1064,7 @@ bool TPlanning_mask::remove_propose(bool verbose)
       {
         remove = (noyes_box(TR("Vuoi annullare tutte le pianificazioni non confermate?")));
         if (remove && get_bool(F_RESCHEDULING) && noyes_box(TR("Vuoi annullare anche le pianificazioni confermate?")))
-          remove_all = TRUE;
+          remove_all = true;
       }
       if (!remove)
         message_box(TR("Nessuna pianificazione da annullare"));  
@@ -1010,7 +1077,7 @@ bool TPlanning_mask::remove_propose(bool verbose)
     add_or_sub_propose(-1, remove_all);
     _proposed_articles.destroy();
   }
-  return TRUE;
+  return true;
 }
 
 void TPlanning_mask::highlight(int row, int col, bool on)
@@ -1032,8 +1099,8 @@ void TPlanning_mask::add_or_sub_propose(char sign, bool scheduled)
     const TMRP_line & a=_proposed_articles[new_row];
     TMSP_line line(a.codclifor(), a.articolo(), a.livgiac(), a.codimp(), a.codlin(), a.codmagdep(), a.codmagdep_coll());
 
-    bool line_found=FALSE;
-    TMSP_constraint*  constraint= find_constraint(line,FALSE);
+    bool line_found=false;
+    TMSP_constraint*  constraint= find_constraint(line,false);
     if (constraint==NULL)
     {
       CHECK( sign>0, "Impossibile trovare il vincolo da soddisfare...");
@@ -1080,7 +1147,7 @@ void TPlanning_mask::add_or_sub_propose(char sign, bool scheduled)
       sf.insert(art_row);
       TToken_string& predrow = sf.row(art_row-1);
       TToken_string& artrow = sf.row(art_row);
-      constraint->fill_sheet_row(artrow, *this,TRUE);
+      constraint->fill_sheet_row(artrow, *this,true);
       artrow.add(predrow.get_long(F_PRIORITA-FIRST_FIELD), F_PRIORITA-FIRST_FIELD);
       artrow.add(get(F_TIPOCF),F_TIPOCF_SHEET-FIRST_FIELD);
       artrow.add(a.codclifor(), F_CLIENTE-FIRST_FIELD);
@@ -1127,7 +1194,7 @@ void TPlanning_mask::add_or_sub_propose(char sign, bool scheduled)
                 art_per_buck, price);
       artrow.add(price.string(), F_BUCKET1 + b*2 + 1 - FIRST_FIELD);
     }
-    test_art_row(art_row,FALSE);
+    test_art_row(art_row,false);
   }
   sf.force_update();
 }
@@ -1192,10 +1259,10 @@ bool TPlanning_mask::sortMSPsheet()
     case SORT_BY_PAC:  a.sort(TRiga_articolo::order_comparePAC); break;
     case SORT_BY_PCA:  a.sort(TRiga_articolo::order_comparePCA); break;
     default:
-      return FALSE;
+      return false;
   }
   a.force_update();
-  return TRUE;
+  return true;
 }
 
 bool TPlanning_mask::sortCRPsheet()
@@ -1204,7 +1271,7 @@ bool TPlanning_mask::sortCRPsheet()
   TSheet_field& a = sfield(F_LINEE);
   a.sort(); 
   a.force_update();
-  return TRUE;
+  return true;
 }
 
 
@@ -1226,23 +1293,24 @@ void TPlanning_mask::propose(int row)
   set(F_USEEXTRAHRS_CRP  ,useextrahours ? "X" : "");
   const TString& rt = get(F_RECALC_TYPE);
   if (rt=="1")
-    propose_1stJIT(_first_fit_logic,TRUE,TRUE, row);
+    propose_1stJIT(_first_fit_logic,true,true, row);
   else if (rt=="1_INFH")
-    propose_1stJIT(_first_fit_logic,TRUE,FALSE, row);
+    propose_1stJIT(_first_fit_logic,true,false, row);
   else if (rt=="1_INF")
-    propose_1stJIT(_first_fit_logic,FALSE,FALSE, row);
+    propose_1stJIT(_first_fit_logic,false,false, row);
   else if (rt=="JIT")
-    propose_1stJIT(_JIT_logic,TRUE,TRUE, row);
+    propose_1stJIT(_JIT_logic,true,true, row);
   else if (rt=="JIT_INFH")
-    propose_1stJIT(_JIT_logic,TRUE,FALSE, row);
+    propose_1stJIT(_JIT_logic,true,false, row);
   else if (rt=="JIT_INF")
-    propose_1stJIT(_JIT_logic,FALSE,FALSE, row);
+    propose_1stJIT(_JIT_logic,false,false, row);
   else if (rt=="UNIL")
-    propose_1stJIT(_uniform_logic,TRUE,FALSE, row);
+    propose_1stJIT(_uniform_logic,true,false, row);
   else if (rt=="UNI")
-    propose_1stJIT(_uniform_logic,FALSE,FALSE, row);
+    propose_1stJIT(_uniform_logic,false,false, row);
   // aggiorna lo sheet delle capacita'
 }
+
 // propone secondo la logica FirstFit o JIT
 void TPlanning_mask::propose_1stJIT(TMSP_logic logic, bool check_machine, bool check_human, int numriga)
 {
@@ -1250,7 +1318,7 @@ void TPlanning_mask::propose_1stJIT(TMSP_logic logic, bool check_machine, bool c
   const bool useextrahours=get_bool(F_USEEXTRAHRS_MSP) ;
   const bool lotsizing=get_bool(F_LOTSIZING) ;
   const bool no_outcapacity=get_bool(F_OUTOFCAPACITY) ;
-  bool ok=TRUE;
+  bool ok=true;
   TWait_cursor clessidra;
   // per sicurezza devo (ri-)calcolare il carico attuale.....  
   _capacities.destroy();
@@ -1258,8 +1326,8 @@ void TPlanning_mask::propose_1stJIT(TMSP_logic logic, bool check_machine, bool c
   {
     if (ok = load_MRP_lines(_actual_plan))
     {
-      gross2net(_actual_plan,FALSE);
-      ok = general_review(check_machine, check_human, useextralines, useextrahours,FALSE, no_outcapacity,0, 0,_actual_plan, logic, TR("Calcolo carico minimo..."));
+      gross2net(_actual_plan,false);
+      ok = general_review(check_machine, check_human, useextralines, useextrahours,false, no_outcapacity,0, 0,_actual_plan, logic, TR("Calcolo carico minimo..."));
     }
   }
   // (two) levels master scheduling
@@ -1267,7 +1335,8 @@ void TPlanning_mask::propose_1stJIT(TMSP_logic logic, bool check_machine, bool c
   int buck=NO_PROPOSE;
   for (int level=1; ok && level <= 2; level++)
   {
-    if (ok = load_MRP_lines(_stock_break, level, numriga))
+    ok = load_MRP_lines(_stock_break, level, numriga);
+    if (ok)
     {
       _proposed_articles.destroy();
       gross2net(_stock_break, lotsizing);
@@ -1275,9 +1344,10 @@ void TPlanning_mask::propose_1stJIT(TMSP_logic logic, bool check_machine, bool c
       msg = (level == 1) ? TR("Calcolo nuove proposte (articoli non Master)") :TR("Calcolo nuove proposte");
       const int  anticipomin=get_int((level == 2) ? F_ANTICIPOMIN : F_ANTICIPOMIN2);
       const int  anticipomax=get_int((level == 2) ? F_ANTICIPOMAX : F_ANTICIPOMAX2);
-      if (ok = general_review(check_machine, check_human, useextralines, useextrahours,lotsizing, no_outcapacity,anticipomin,anticipomax,_stock_break, logic, msg))
+      ok = general_review(check_machine, check_human, useextralines, useextrahours,lotsizing, no_outcapacity,anticipomin,anticipomax,_stock_break, logic, msg);
+      if (ok)
       {
-        int buck2 = insert_propose(FALSE);
+        const int buck2 = insert_propose(false);
         buck = min (buck,buck2);
         if (level!=2)
           last_propose.add(_proposed_articles);
@@ -1308,6 +1378,12 @@ void TPlanning_mask::propose_1stJIT(TMSP_logic logic, bool check_machine, bool c
 // cerca il primo bucket con capacit� produttiva
 bool TPlanning_mask::general_review(bool check_machine, bool check_human, bool useextralines, bool useextrahours,bool lotsizing, bool no_outcapacity, int  anticipomin,int  anticipomax, TMSP_mode mode, TMSP_logic logic, const char * msg )
 {
+  const long max_mrp_rows=_mrp_articles.items();
+  if (max_mrp_rows == 0)
+    return true;
+
+  TProgind pi((max_mrp_rows+1)*LAST_BUCKET ,msg, true, true);
+
   const bool ignore_mag=get_bool(F_NOMAG_IN);
   const bool ignore_imp=get_bool(F_NOIMP_IN);
   const bool ignore_lin=get_bool(F_NOLIN_IN);
@@ -1315,9 +1391,6 @@ bool TPlanning_mask::general_review(bool check_machine, bool check_human, bool u
   TLinea_prod linea_prod;
   TArray labors;
 
-  const long max_mrp_rows=_mrp_articles.items();
-  TProgind pi((max_mrp_rows+1)*LAST_BUCKET ,msg, TRUE, TRUE);
-  
   for (int bucket = 0; bucket < LAST_BUCKET ; bucket++)
   {
     pi.addstatus(1);
@@ -1325,16 +1398,18 @@ bool TPlanning_mask::general_review(bool check_machine, bool check_human, bool u
     {
       pi.addstatus(1);
       if (pi.iscancelled()) 
-        return FALSE;
+        return false;
       TMRP_line &mrpline=_mrp_articles[mrp_row];
       TDate data_buck(starting_date());
       data_buck+=days_per_bucket()*(bucket-1);
       round_date(data_buck);
       const TMRP_time mrp_time(data_buck, 0, "","");
       TMRP_record & mrp_rec= mrpline.record(mrp_time);
-      real pieces, curr_arts, art_per_buck(mrp_rec.net_requirement()); // quantit� da produrre nel bucket
+      real art_per_buck = mrp_rec.net_requirement(); // quantit� da produrre nel bucket
       if (art_per_buck>ZERO)
       {
+        real pieces, curr_arts; 
+  
         int lastbuck =mrpline.last_bucket();
         TString16 livello_di_giacenza(mrpline.livgiac());
         TString8 codlin(mrpline.codlin());
@@ -1371,7 +1446,14 @@ bool TPlanning_mask::general_review(bool check_machine, bool check_human, bool u
               art_per_buck = mrpline.net_requirement(lastbuck) ;
               mrpline.set_net_req(bucket,art_per_buck);
             }
-            while (art_per_buck > ZERO && attemp <= 3) 
+
+            int max_attempts = 3;
+
+            // non anticipare articoli che potrebbero avere figli non anticipati automaticamente
+            if (!no_limits && get_bool(F_NOANTICIPI_MSP)) 
+              max_attempts = 2;
+
+            while (art_per_buck > ZERO && attemp <= max_attempts) 
             {
               if (logic == _JIT_logic)
               {
@@ -1414,7 +1496,7 @@ bool TPlanning_mask::general_review(bool check_machine, bool check_human, bool u
                     crpline_lin = _capacities.find(linea_prod);
                     if (crpline_lin == NULL)
                       crpline_lin = compute_capacity(linea_prod,useextralines, useextrahours);
-                    crpline_art = _capacities.find(codimplin, linea_prod.codice(), mrpline.articolo(), mrpline.codclifor(),TRUE);
+                    crpline_art = _capacities.find(codimplin, linea_prod.codice(), mrpline.articolo(), mrpline.codclifor(),true);
                     crpline_imp = _capacities.find(codimplin);
                     crpline_firm = _capacities.find();
                     int human_level = 1;
@@ -1468,7 +1550,7 @@ bool TPlanning_mask::general_review(bool check_machine, bool check_human, bool u
                       {
                         TMRP_line* new_article = _proposed_articles.find(mrpline.codice(),
                                 mrpline.livgiac(), mrpline.codmagdep(), 
-                                  linea_prod.codimp() , linea_prod.codice(), mrpline.codcli(), TRUE);
+                                  linea_prod.codimp() , linea_prod.codice(), mrpline.codcli(), true);
                         add_MRP_bucket(*new_article, nbucket, curr_arts-art_per_buck );
                       }*/
                     }
@@ -1485,20 +1567,14 @@ bool TPlanning_mask::general_review(bool check_machine, bool check_human, bool u
                       crpline_lin->load(nbucket).add_pieces(pieces);
                       crpline_imp->load(nbucket).add_pieces(pieces);
                       // aggiunge l'impegno finanziario
-                      pieces = curr_arts * cache().get(LF_ANAMAG,mrpline.articolo()).get_real(ANAMAG_COSTSTD);
+                      const real pieces = curr_arts * cache().get(LF_ANAMAG,mrpline.articolo()).get_real(ANAMAG_COSTSTD);
                       crpline_art->load(nbucket).add_money(pieces);
                       crpline_lin->load(nbucket).add_money(pieces);
                       crpline_imp->load(nbucket).add_money(pieces);
                       hload = load*curr_labor->numpers_linea(nlinea);
-                      switch (human_level)
-                      {
-                        case 3:
-                          crpline_lin->load(nbucket).add_human(hload);
-                        case 2:
-                          crpline_imp->load(nbucket).add_human(hload);
-                        case 1:
-                          crpline_firm->load(nbucket).add_human(hload);
-                      }
+                      crpline_lin->load(nbucket).add_human(hload);
+                      crpline_imp->load(nbucket).add_human(hload);
+                      crpline_firm->load(nbucket).add_human(hload);
                       crpline_art->load(nbucket).add_human(hload) ;
                       if (mode == _stock_break)
                       {
@@ -1509,7 +1585,7 @@ bool TPlanning_mask::general_review(bool check_machine, bool check_human, bool u
                         if (codmagc.blank())
                           codmagc = linea_prod.codmagdep_coll();
                         TMRP_line* new_article = find_propose(mrpline.codclifor(), mrpline.articolo(),
-                                mrpline.livgiac(), codimplin , linea_prod.codice(), codmag, codmagc, TRUE);
+                                mrpline.livgiac(), codimplin , linea_prod.codice(), codmag, codmagc, true);
                         add_MRP_bucket(*new_article, nbucket, curr_arts);
                       }
                     }
@@ -1593,7 +1669,7 @@ bool TPlanning_mask::general_review(bool check_machine, bool check_human, bool u
                 }
               }
               TMRP_line* new_article = find_propose(codclifor, mrpline.articolo(), mrpline.livgiac(), 
-                      mrpline.codimp() , mrpline.codlin(), codmagdep, mrpline.codmagdep_coll(), TRUE);
+                      mrpline.codimp() , mrpline.codlin(), codmagdep, mrpline.codmagdep_coll(), true);
               curr_arts = art_per_buck;
               if (logic == _uniform_logic)
                 curr_arts /= (upper_buck-nbucket+1);
@@ -1625,7 +1701,7 @@ bool TPlanning_mask::general_review(bool check_machine, bool check_human, bool u
       }
     }
   }
-  return TRUE;
+  return true;
 }
 
 
@@ -1634,15 +1710,15 @@ bool TPlanning_mask::capacity_review(bool useextralines, bool useextrahours)
   bool ok;
   TWait_cursor clessidra;
   if (!load_MRP_lines(_actual_plan))
-    return FALSE;
+    return false;
   gross2net(_actual_plan);
 
   _capacities.destroy();
   const char *msg=TR("Calcolo carico attuale...");
   if (get(F_RECALC_TYPE).left(1)=="1")
-    ok = general_review(TRUE, TRUE, useextralines, useextrahours, FALSE, FALSE, 0, 0, _actual_plan,_first_fit_logic, msg);
+    ok = general_review(true, true, useextralines, useextrahours, false, false, 0, 0, _actual_plan,_first_fit_logic, msg);
   else if (get(F_RECALC_TYPE).left(3)=="JIT")
-    ok = general_review(TRUE, TRUE, useextralines, useextrahours, FALSE, FALSE, 0, 0, _actual_plan,_first_fit_logic, msg);
+    ok = general_review(true, true, useextralines, useextrahours, false, false, 0, 0, _actual_plan,_first_fit_logic, msg);
 
   _capacities.sort();
   return ok;
@@ -1653,17 +1729,14 @@ TCRP_line *TPlanning_mask::compute_capacity(TLinea_prod &lineaprod, bool useextr
 {
   TString8 codlin(lineaprod.codice());
   TString8 codimp(lineaprod.codimp());
-  TMRP_calendar & cal = TMRP_time::get_calendar("", codlin);
-  TMRP_calendar & cal_imp = TMRP_time::get_calendar(codimp);
-  TMRP_calendar & cal_firm = TMRP_time::get_calendar();
-  CHECK(_capacities.find(lineaprod,FALSE)==NULL,"Errore: impossibile ricalcolare la capacit� di una linea produttiva");
+  CHECK(_capacities.find(lineaprod,false)==NULL,"Errore: impossibile ricalcolare la capacit� di una linea produttiva");
 
   TCRP_line *crpline_lin,*crpline_imp,*crpline_firm;
-  crpline_lin     =_capacities.find(lineaprod, "", 0L,TRUE);
+  crpline_lin     =_capacities.find(lineaprod, "", 0L,true);
   const bool compute_imp = (_capacities.find(codimp, "", "", 0L)==NULL);
-  crpline_imp =_capacities.find(codimp, "", "", 0L, TRUE);
+  crpline_imp =_capacities.find(codimp, "", "", 0L, true);
   const bool compute_firm = (_capacities.find("", "", "", 0L)==NULL);
-  crpline_firm=_capacities.find("", "", "", 0L, TRUE);
+  crpline_firm=_capacities.find("", "", "", 0L, true);
 
   // calcola la capacita'
   TDate data_buck=starting_date();
@@ -1679,13 +1752,20 @@ TCRP_line *TPlanning_mask::compute_capacity(TLinea_prod &lineaprod, bool useextr
     round_date(next_data_buck);
     while (data_buck < next_data_buck)
     {
+      const TMRP_calendar& cal = TMRP_time::get_calendar("", codlin);
       cal.add_oremacchina(capacity, data_buck,useextrahours);
       if (lineaprod.personale_dedicato())
         cal.add_oreuomo(human, data_buck,useextrahours);
       if (compute_imp && lineaprod.get_impianto() && lineaprod.get_impianto()->personale_dedicato())
+      {
+        const TMRP_calendar& cal_imp = TMRP_time::get_calendar(codimp);
         cal_imp.add_oreuomo(human_imp, data_buck,useextrahours);
+      }
       if (compute_firm)
+      {
+        const TMRP_calendar& cal_firm = TMRP_time::get_calendar();
         cal_firm.add_oreuomo(human_firm, data_buck,useextrahours);
+      }
       ++data_buck;
     }
     crpline_lin->capacity(b).set_machine(capacity);
@@ -1732,6 +1812,7 @@ void TPlanning_mask::msprow2codes(TToken_string &row,long &clifor, TCodice_artic
     add_depcode(mag,row.get(F_DEPOSITO-FIRST_FIELD));
     add_magcode(magc,row.get(F_MAG_COLL-FIRST_FIELD));
     add_depcode(magc,row.get(F_DEP_COLL-FIRST_FIELD));
+
     imp = row.get(F_CODIMP-FIRST_FIELD); imp.trim();
     lin = row.get(F_CODLIN-FIRST_FIELD); lin.trim();
     um = row.get(F_UM-FIRST_FIELD); um.trim();
@@ -1758,7 +1839,7 @@ bool TPlanning_mask::load_MRP_lines(TMSP_mode mode, int level, int numriga)
   if (sa.items()==0)
   {
     message_box(TR("Nessun articolo da valutare"));
-    return FALSE;
+    return false;
   }
   TWait_cursor hourglass;
   int first_row=-1, last_row=-1;
@@ -1774,7 +1855,7 @@ bool TPlanning_mask::load_MRP_lines(TMSP_mode mode, int level, int numriga)
   // calcola gli impegni di produzione per gli articoli dello sheet
   TMRP_line* curr_article=NULL;
   int added_on = -1;
-  bool skip=FALSE;
+  bool skip=false;
   FOR_EACH_SHEET_ROW(sa, r, row) if (!sa.cell_disabled(r, a_buck0+2) || sa.cell_disabled(r+1, a_buck0+2))
   {
     if (first_row < 0 || r >=first_row && r <=last_row)
@@ -1803,10 +1884,10 @@ bool TPlanning_mask::load_MRP_lines(TMSP_mode mode, int level, int numriga)
             (!is_constraint && mode == _actual_plan) ||
               (is_constraint && mode == _rescheduling) )
         {
-          curr_article = _mrp_articles.find(art, liv, mag, magc, imp, lin, clifor ,TRUE);
+          curr_article = _mrp_articles.find(art, liv, mag, magc, imp, lin, clifor ,true);
           added_on = -1;
         }
-        TMSP_line* mspline = _articles.find(*row, FALSE);
+        TMSP_line* mspline = _articles.find(*row, false);
   
         if ((mode == _stock_break ) ||
             (!is_constraint && mode == _actual_plan) ||
@@ -1879,7 +1960,7 @@ bool TPlanning_mask::load_MRP_lines(TMSP_mode mode, int level, int numriga)
       }
     }
   }
-  return TRUE;
+  return true;
 }
 
 // already_net: dice se le quantit� presenti sono da considerare gia' come net req o 
@@ -1905,21 +1986,25 @@ bool TPlanning_mask::gross2net(TMSP_mode mode, bool lotsizing)
           mrpline.set_net_req(bucket, netreq);
           break;
         case _stock_break:
-          giacres  = mrpline.on_hand(bucket);
-          giacres -= mrpline.gross_requirement(bucket);
-          //if (bucket == 0)
-            giacres += mrpline.planned_orders(bucket);
-          giacres += mrpline.sched_receipts(bucket);
-          if (lotsizing)                                       
-            netreq = mrpline.sizeup_net_requirement(bucket, giacres, netreq);
-          else
           {
-            netreq = -giacres;
-            netreq = mrpline.set_net_req(bucket, netreq);
+            giacres  = mrpline.on_hand(bucket);
+            giacres -= mrpline.gross_requirement(bucket);
+            //if (bucket == 0)
+              giacres += mrpline.planned_orders(bucket);
+            giacres += mrpline.sched_receipts(bucket);
+            if (lotsizing)                                       
+              netreq = mrpline.sizeup_net_requirement(bucket, giacres, netreq);
+            else
+            {
+              netreq = -giacres;
+              netreq = mrpline.set_net_req(bucket, netreq);
+            }
+            const int nb = mrpline.next_bucket(bucket);
+            if (nb <= mrpline.last_bucket())
+              mrpline.set_on_hand(nb, giacres);
           }
-          const int nb = mrpline.next_bucket(bucket);
-          if (nb <= mrpline.last_bucket())
-            mrpline.set_on_hand(nb, giacres);
+          break;
+        default:
           break;
       }
     }
@@ -1938,7 +2023,7 @@ const TDate & TPlanning_mask::starting_date() const
     else
     {
       nakedate = TODAY;
-      round_date(nakedate, TRUE, FALSE);
+      round_date(nakedate, true, false);
       nakedate+=1;
     }
   }
@@ -2031,7 +2116,7 @@ int TPlanning_mask::init_bucket0(TArticolo_giacenza &art, int r)
   if (ord_row.get_char(F_MASTERCODE-FIRST_FIELD) == MASTERCODE_CHAR)
     art_row.add(get_int(F_2LEVEL_PRIORITY),F_PRIORITA-FIRST_FIELD);
   
-  do_test_art_row(r,c,r,FALSE);
+  do_test_art_row(r,c,r,false);
 
   return c-2;
 }
@@ -2046,15 +2131,21 @@ bool TPlanning_mask::do_test_art_row(int r, int first, int last, bool signal)
 
   // **********
   // setta la priorita' su tutte le righe del blocco
-  const int prior    =curr_row.get_int(sf.cid2index(F_PRIORITA));
-  const int old_prior=constr_row.get_int(sf.cid2index(F_PRIORITA));
-  if (old_prior != prior)
+  TString16 prior = curr_row.get(sf.cid2index(F_PRIORITA)); prior.trim();
+  TString16 old_prior=constr_row.get(sf.cid2index(F_PRIORITA)); old_prior.trim();
+  if (prior != old_prior)
   {
-    for (int i = first-1; i<=last; i++)
+    if (prior.not_empty())
     {
-      sf.row( i ).add(prior , sf.cid2index(F_PRIORITA));
-      sf.force_update(i);
+      for (int i = first-1; i<=last; i++)
+      {
+        sf.row( i ).add(prior , sf.cid2index(F_PRIORITA));
+        sf.force_update(i);
+      }
     }
+    else
+      sf.row(r).add(old_prior, sf.cid2index(F_PRIORITA));
+
   }
   // **********
   // calcola la giacenza proiettata
@@ -2064,7 +2155,7 @@ bool TPlanning_mask::do_test_art_row(int r, int first, int last, bool signal)
     if (signal)
     {             
       error_box(FR("Articolo nullo nella riga %d"), r+1);
-      signal = FALSE;
+      signal = false;
     }
     return signal;
   }
@@ -2090,9 +2181,9 @@ bool TPlanning_mask::do_test_art_row(int r, int first, int last, bool signal)
   switch (*get(F_SOGLIAATT))
   {
     case 'S': 
-      soglia = art.scorta_minima(mag, liv, 0, FALSE); break;
+      soglia = art.scorta_minima(mag, liv, 0, false); break;
     case 'R': 
-      soglia = art.scorta_minima(mag, liv, 0, TRUE);  break;
+      soglia = art.scorta_minima(mag, liv, 0, true);  break;
     default:  
       soglia = ZERO;
   }
@@ -2116,7 +2207,7 @@ bool TPlanning_mask::do_test_art_row(int r, int first, int last, bool signal)
       round_date(d);
       err << TR("Riga ") << first+1 << ": Vincolo non ripettato al " << d;
       beep();
-      signal =FALSE;
+      signal =false;
       xvt_statbar_set(err);
     }
   }
@@ -2146,7 +2237,7 @@ bool TPlanning_mask::do_test_art_row(int r, int first, int last, bool signal)
     }
     while (art2ndlev=currconstr->get_unused_line2())
     {
-      do_test_art_2ndlevel(art2ndlev,TRUE);
+      do_test_art_2ndlevel(art2ndlev,true);
       currconstr->discard_line2(art2ndlev);
     }
   }
@@ -2154,7 +2245,7 @@ bool TPlanning_mask::do_test_art_row(int r, int first, int last, bool signal)
 }
 
 //
-// controlla la dipendenza tra articoli MAster e dipendenti
+// controlla la dipendenza tra articoli Master e dipendenti
 void TPlanning_mask::do_test_art_2ndlevel(TMSP_line2 *art2ndlev, bool erase)
 {
   TSheet_field& sf = sfield(F_ARTICOLI);
@@ -2167,13 +2258,13 @@ void TPlanning_mask::do_test_art_2ndlevel(TMSP_line2 *art2ndlev, bool erase)
       , mc->livello(), mc->codimp(), mc->codlin(), mc->codmagdep());
     if (master_constr==NULL)
     {
-      master_constr=_constraints.find(art2ndlev->constraint().codclifor(),mc->articolo(), mc->livello(), mc->codimp(), mc->codlin(), mc->codmagdep(), TRUE);
+      master_constr=_constraints.find(art2ndlev->constraint().codclifor(),mc->articolo(), mc->livello(), mc->codimp(), mc->codlin(), mc->codmagdep(), true);
     }
 
     int mrow= find_constr_row(*master_constr);
     TMSP_constraint* upperline=master_constr->get_upperline(art2ndlev->constraint());
     real difference;
-    bool changed=FALSE;
+    bool changed=false;
     for (int b = 0; b <= LAST_BUCKET; b++)
     {
       const int b2=b-int(((real)(mc->leadtime()/days_per_bucket()+0.5)).integer());
@@ -2192,7 +2283,7 @@ void TPlanning_mask::do_test_art_2ndlevel(TMSP_line2 *art2ndlev, bool erase)
           // ricostruisce il vincolo della linea master sullo sheet
           TToken_string &master_row=sf.row(mrow);
           master_row.add(master_constr->qta(b2).string(),sf.cid2index(F_BUCKET0+b2*2));
-          changed=TRUE;
+          changed=true;
         }
       }
     }
@@ -2201,7 +2292,7 @@ void TPlanning_mask::do_test_art_2ndlevel(TMSP_line2 *art2ndlev, bool erase)
       sf.force_update(mrow);
       int first,last;
       TRiga_articolo::find_block(sf, mrow+2, first, last);
-      do_test_art_row(mrow+2, first, last, FALSE);
+      do_test_art_row(mrow+2, first, last, false);
     }
   }
 }
@@ -2211,14 +2302,14 @@ bool TPlanning_mask::pack_article_sheet(int r, int first, int last)
 {
   TSheet_field& sf = sfield(F_ARTICOLI);
   TToken_string &art_row = sf.row(r);
-  bool packed = FALSE;
+  bool packed = false;
   for (int  curr=last; curr >=first; curr--) if (curr != r)
   {
     TToken_string &curr_row=sf.row(curr); 
     if (art_row.get_long(F_CLIENTE-FIRST_FIELD) == curr_row.get_long(F_CLIENTE-FIRST_FIELD))
     if (TRiga_articolo ::order_compare(art_row, curr_row,15)==0)
     {
-      packed = TRUE;
+      packed = true;
       TToken_string work_row = curr_row;
       for (int bucket=0; packed && bucket<=LAST_BUCKET ; bucket++)
       {
@@ -2227,7 +2318,7 @@ bool TPlanning_mask::pack_article_sheet(int r, int first, int last)
         real prz1(art_row.get(F_BUCKET1 +1 + bucket*2 - FIRST_FIELD));
         real prz2(work_row.get(F_BUCKET1 +1 + bucket*2 - FIRST_FIELD));
         if (!prz1.is_zero() && !qta2.is_zero() && prz1 != prz2)
-          packed = FALSE;
+          packed = false;
         if (qta2.is_zero())
           work_row.add(prz1.string(), F_BUCKET1 + 1 + bucket*2 - FIRST_FIELD);
         qta2 += qta1;
@@ -2252,7 +2343,7 @@ bool TPlanning_mask::pack_article_sheet(int r, int first, int last)
 // controllo linee in modo interattivo
 bool TPlanning_mask::test_art_row(int r, bool signal)
 {
-  bool ok = TRUE;
+  bool ok = true;
   TSheet_field& sf = sfield(F_ARTICOLI);
   int first,last;
   if (TRiga_articolo::find_block(sf, r, first, last))
@@ -2264,7 +2355,7 @@ bool TPlanning_mask::test_art_row(int r, bool signal)
     if (signal) 
     {
       // interactive mode:
-      TMSP_line* line = _articles.find(curr_row, FALSE);
+      TMSP_line* line = _articles.find(curr_row, false);
       if (line)
       {
         real value,goodvalue;
@@ -2278,7 +2369,7 @@ bool TPlanning_mask::test_art_row(int r, bool signal)
             {
               error_box(FR("Impossibile modificare la quantita' per l'articolo %s, colonna %d"),(const char *)line->articolo(),b);
               do_events();
-              ok = FALSE;
+              ok = false;
             } 
           } else {
             goodvalue = line->qta_min(b);
@@ -2293,7 +2384,7 @@ bool TPlanning_mask::test_art_row(int r, bool signal)
                     xvt_statbar_set(msg);
                 } else {
                   error_box(msg);
-                  ok = FALSE;
+                  ok = false;
                 }
                 do_events();
               }      
@@ -2316,7 +2407,7 @@ bool TPlanning_mask::test_load_row(int r, bool signal)
   TSheet_field& sf = sfield(F_LINEE);
   const int narticoli=sf.items();
   if (narticoli<=r)
-    return TRUE;
+    return true;
   // Calcola l'indice c della riga con la capacita'
   const int b0 = sf.cid2index(F_LBUCKET0);
   const int b1 = sf.cid2index(F_LBUCKET1);
@@ -2341,7 +2432,7 @@ bool TPlanning_mask::test_load_row(int r, bool signal)
       round_date(d);
       err << TR("Riga ") << c+1 << TR(": capacit� superata al ") << d;
       beep();
-      signal =FALSE;
+      signal =false;
       xvt_statbar_set(err);
     }
   }
@@ -2380,11 +2471,11 @@ int TPlanning_mask::salva_cella(int r, int b, TPlan_docs &doc_rows, TToken_strin
   TDate datacons = from + long(bucket_size * (b-1));
   
   //if (datacons > date_to)
-  //  return FALSE;
+  //  return false;
   round_date(datacons, !bucket_mese());
 
   TToken_string & row = sf.row(r);
-  TMSP_line       &line       = *_articles.find(row, TRUE);
+  TMSP_line       &line       = *_articles.find(row, true);
   TMSP_constraint *constraint = find_constraint(line);
   TMRP_line        *mrpline   = _mrp_articles.find(constraint->articolo(),constraint->livgiac(),
       constraint->codmagdep(),constraint->codmagdep_coll(), constraint->codimp(), constraint->codlin(), constraint->codclifor());
@@ -2442,12 +2533,12 @@ int TPlanning_mask::salva_cella(int r, int b, TPlan_docs &doc_rows, TToken_strin
         }
       }   
       TMRP_docref *rdr=line.first_rigaref(b);
-      bool found=FALSE;
-      while (rdr || found==FALSE && new_val.sign() > 0)
+      bool found=false;
+      while (rdr || found==false && new_val.sign() > 0)
       {
         if (rdr==NULL && !found)
         {
-          found=TRUE;
+          found=true;
           rdr=new TMRP_docref(new_anno,new_codnum,new_numdoc,new_numrig,row.get(sf.cid2index(F_UM)),ZERO,ZERO);
           line.add_rigaref(b, rdr);
         }
@@ -2503,7 +2594,54 @@ int TPlanning_mask::salva_cella(int r, int b, TPlan_docs &doc_rows, TToken_strin
                 riga.put(RDOC_UMQTA, row.get(sf.cid2index(F_UM)));
                 riga.put(RDOC_DATACONS, datacons);
                 riga.put(RDOC_DESCR, row.get(sf.cid2index(F_DESCART)));
-            
+
+								TMSP_constraint *c = find_constraint(line);
+
+                if (c != NULL)
+                {
+		              const TRectype* dardoc = NULL;
+
+									for (int buck = b; (dardoc == NULL) && (buck < LAST_BUCKET); buck++)
+									{
+										const int refs = c->rigarefs(buck);
+										if (refs > 0)
+										{
+											const TMRP_docref* dr = c->rigaref(buck, 0);
+											dardoc = &dr->get_rdoc();
+										}
+									}
+									if (dardoc == NULL && b > 0)
+									{
+										for (int buck = b - 1; (dardoc == NULL) && (buck >= 0); buck--)
+										{
+											const int refs = c->rigarefs(buck);
+											if (refs > 0)
+											{
+											  const TMRP_docref* dr = c->rigaref(buck, 0);
+											  dardoc = &dr->get_rdoc();
+                      }
+                    }
+									}
+									if (dardoc != NULL)
+									{
+										const int depth = get_int(F_RIFERIMENTO_MSP);
+										riga.set_original_rdoc_key(*dardoc, depth);
+										riga.put(RDOC_QTAGG5, dardoc->get_int(RDOC_QTAGG5));                // Per ora memorizziamo in QTAGG5, scelto a caso
+									}
+									else
+                  {
+										TString msg; msg.format(FR("Riferimento non trovato : riga %d"), r);
+                    xvt_statbar_set(msg);
+                    beep();
+                  }
+                }
+								else
+                {
+									TString msg; msg.format(FR("Vincolo non trovato : riga %"), r);
+                  xvt_statbar_set(msg);
+                  beep();
+                }
+
                 TRectype& doc = (TRectype&)riga.doc().head();
                 if (doc.get(DOC_DATACONS).empty())
                 {
@@ -2542,7 +2680,7 @@ int TPlanning_mask::salva_cella(int r, int b, TPlan_docs &doc_rows, TToken_strin
           }
         }
         else
-          found = TRUE;
+          found = true;
         rdr=line.next_rigaref(b);
       }  // ciclo di aggiornamento dei riferimenti ai docs
       return 1;
@@ -2579,7 +2717,7 @@ int TPlanning_mask::salva_documenti(TExceptions_array &excepts, TSheet_field & s
         if (!noyes_box(TR("E' stato scelto di generare un unico ordine per ogni articolo e scadenza: confermare?")))
           return 0;
     
-      TProgind pi(LAST_BUCKET*sf.items(), TR("Emissione documenti") , FALSE, TRUE);
+      TProgind pi(LAST_BUCKET*sf.items(), TR("Emissione documenti") , false, true);
       if (ordiniXscadenza)
       {
         // *************************
@@ -2682,7 +2820,7 @@ bool TPlanning_mask::on_savefields_event(long jolly)
     {
       tmp = sf.row(nriga).get(sf.cid2index(F_NUM_PLAN));
       if (tmp.empty())
-        return TRUE;
+        return true;
       const TSheet_field& num_s = sfield(F_NUM_PLA);
       FOR_EACH_SHEET_ROW_BACK(num_s, r, row)
         if (tmp == row->get(num_s.cid2index(F_NUMERAZ)))
@@ -2700,7 +2838,7 @@ bool TPlanning_mask::on_savefields_event(long jolly)
         return sf.error_box(FR("Tipo documento '%s' non incluso tra quelli di planning"), (const char *)tmp);
     }
   } while (--nriga >= 0 && jolly < 0);
-  return TRUE;
+  return true;
 }
 
 bool TPlanning_mask::on_field_event(TOperable_field& o, TField_event e, long jolly)
@@ -2712,12 +2850,12 @@ bool TPlanning_mask::on_field_event(TOperable_field& o, TField_event e, long jol
     if (e == fe_modify)
     {
       _start_date = NULLDATE;
-      round_field(o, FALSE);
+      round_field(o, false);
     }
     break;
   case F_ADATA:
     if (e == fe_modify)
-      round_field(o, TRUE, FALSE);
+      round_field(o, true, false);
     break;
   case F_BUCKET:
     if (e == fe_modify)
@@ -2819,7 +2957,7 @@ bool TPlanning_mask::on_field_event(TOperable_field& o, TField_event e, long jol
       switch(e)
       {
       case se_query_add:
-        return FALSE;
+        return false;
       case se_leave:
         test_load_row((int)jolly);
         break;
@@ -2923,7 +3061,7 @@ bool TPlanning_mask::on_field_event(TOperable_field& o, TField_event e, long jol
       {
         // controla se il magazzino richiede dep
         if (_magazzini.get(m.get(F_MAGAZZINO)).get_bool("B0"))
-          return FALSE;
+          return false;
       }
     }
     break;
@@ -2966,7 +3104,7 @@ bool TPlanning_mask::on_field_event(TOperable_field& o, TField_event e, long jol
         {
           clear_sheets();
         } else
-          return FALSE;
+          return false;
       }
     break;
   case DLG_ELABORA:
@@ -3007,7 +3145,7 @@ bool TPlanning_mask::on_field_event(TOperable_field& o, TField_event e, long jol
   case F_CANCEL_MSP:
     if (e == fe_button)
     {
-      remove_propose(TRUE);
+      remove_propose(true);
     }
     break;
   case F_RECALC_MSP:
@@ -3076,7 +3214,7 @@ bool TPlanning_mask::on_field_event(TOperable_field& o, TField_event e, long jol
           if (m.run() != K_ESC)
             m.edit_checked();
         }
-        return TRUE;
+        return true;
       }
       message_box(TR("Nessun ordine pianificato per la riga corrente"));
     }
@@ -3103,7 +3241,7 @@ bool TPlanning_mask::on_field_event(TOperable_field& o, TField_event e, long jol
             {
               if (m.run()!= K_ESC)
                 m.edit_checked();
-              return TRUE;
+              return true;
             }
           }
           break;
@@ -3114,7 +3252,7 @@ bool TPlanning_mask::on_field_event(TOperable_field& o, TField_event e, long jol
               m.run();
             else
               message_box(TR("Nessun vincolo interno sulla riga corrente"));
-            return TRUE;
+            return true;
           }
           break;
           case F_VINCOLI_OUT:
@@ -3124,7 +3262,7 @@ bool TPlanning_mask::on_field_event(TOperable_field& o, TField_event e, long jol
               m.run();
             else
               message_box(TR("Nessun articolo Master dipendente dalla riga corrente"));
-            return TRUE;
+            return true;
           }
           break;                                 
         }
@@ -3189,7 +3327,7 @@ bool TPlanning_mask::on_field_event(TOperable_field& o, TField_event e, long jol
         TSheet_field& s = sfield(F_ARTICOLI);
         int lineeart=s.items();
         if (lineeart>0 && s.dirty() && !yesno_box(confirm_msg,lineeart))
-          return FALSE;
+          return false;
       }
     break;
   case F_SHRINK_ALL:
@@ -3241,7 +3379,7 @@ bool TPlanning_mask::on_field_event(TOperable_field& o, TField_event e, long jol
   default:
     break;
   }
-  return TRUE;
+  return true;
 }
 
 TPlanning_mask::TPlanning_mask(const char * name)
@@ -3259,7 +3397,7 @@ TPlanning_mask::TPlanning_mask()
 void TPlanning_mask::init()
 {
   TSheet_field& sf = sfield(F_ARTICOLI);
-  sf.set_append(FALSE);
+  sf.set_append(false);
 
   for (short l = 0; l < 4; l++)
     livelli_giacenza().set_sheetcolumn(sf, F_LIV1+l, l+1);
@@ -3308,7 +3446,7 @@ void TMSPCheck_mask::gopos_mainmask()
   while (sf.cell_disabled(curr_row,F_BUCKET1-FIRST_FIELD) )
     curr_row++;
 
-  sf.select(curr_row/*,TRUE*/);
+  sf.select(curr_row/*,true*/);
   _main_mask->set_focus_field(sf.dlg());
   sf.set_focus_cell(curr_row, last_col()*2+F_BUCKET0);
 }
@@ -3357,16 +3495,16 @@ int TMSPCheck_mask::fill_mask(const bool show_fields)
     _constr_row=find_constr_row(_row);
     set(FC_RIGA,_row+1); 
     field(FC_CODCLI).set_prompt(_main_mask->get(F_TIPOCF)[0]=='C' ? "Cliente":"Fornitore");
-    set(FC_CODCLI,codcli, TRUE);
-    set(FC_CODART,codart, TRUE); 
+    set(FC_CODCLI,codcli, true);
+    set(FC_CODART,codart, true); 
     for (int l= livelli_giacenza().last_level(); l >= 1 ; l--)
-      set(FC_LIV1+l-1, livelli_giacenza().unpack_grpcode(liv,l), TRUE);
-    set(FC_CODIMP,codimp, TRUE);
-    set(FC_CODLIN,codlin, TRUE);
-    set(FC_CODMAG,mag.left(3), TRUE);
-    set(FC_CODDEP,mag.mid(3), TRUE);
-    //set(FC_CODMAG_C,magc.left(3), TRUE);
-    //set(FC_CODDEP_C,magc.mid(3), TRUE);
+      set(FC_LIV1+l-1, livelli_giacenza().unpack_grpcode(liv,l), true);
+    set(FC_CODIMP,codimp, true);
+    set(FC_CODLIN,codlin, true);
+    set(FC_CODMAG,mag.left(3), true);
+    set(FC_CODDEP,mag.mid(3), true);
+    //set(FC_CODMAG_C,magc.left(3), true);
+    //set(FC_CODDEP_C,magc.mid(3), true);
   }
   set(FC_BUCKET,_col);
   TDate data_buck(_main_mask->starting_date());
@@ -3418,16 +3556,16 @@ int TMSPCheck_mask::fill_mask(const bool show_fields)
     switch (*_main_mask->get(F_SOGLIAATT))
     {
       case 'R': 
-        soglia = art.scorta_minima(mag, liv, 0, TRUE);  
+        soglia = art.scorta_minima(mag, liv, 0, true);  
         if (!soglia.is_zero()) break;
       case 'S': 
-        soglia = art.scorta_minima(mag, liv, 0, FALSE); break;
+        soglia = art.scorta_minima(mag, liv, 0, false); break;
       default:  
         soglia = ZERO;
     }
     soglia = soglia -0.01;
     bool stockbreak = stock < soglia;
-    bool overgiac = FALSE;
+    bool overgiac = false;
     set(FC_GIAC,stock.string());
     show(FC_GIAC,       stock > ZERO);
     stock = soglia - stock;
@@ -3486,7 +3624,7 @@ int TMSPCheck_mask::fill_mask(const bool show_fields)
     {
       return _sheet->row(_row-1).get_char(F_MASTERCODE-FIRST_FIELD)==MASTERCODE_CHAR;
     }
-    return FALSE;
+    return false;
   }
   else
     return error;
@@ -3512,7 +3650,7 @@ bool TMSPCheck_mask::on_field_event(TOperable_field& o, TField_event e, long jol
   if (e==fe_button)
   {
     const int dlg=o.dlg();
-    bool redo=TRUE;
+    bool redo=true;
     const int findfilter=get_int(FC_FINDFILTER);
     const TString4 old_movefilter(get(FC_MOVEFILTER));
     const TString4 new_movefilter(findfilter & 1 ? "" : "C");
@@ -3540,7 +3678,7 @@ bool TMSPCheck_mask::on_field_event(TOperable_field& o, TField_event e, long jol
             if (findfilter<0 && err || err & findfilter)
             {
               set(FC_MOVEFILTER,old_movefilter);
-              return TRUE;
+              return true;
             }
           }
           if (redo = move_to(FC_UP))
@@ -3562,7 +3700,7 @@ bool TMSPCheck_mask::on_field_event(TOperable_field& o, TField_event e, long jol
             if (findfilter<0 && err || err & findfilter)
             {
               set(FC_MOVEFILTER,old_movefilter);
-              return TRUE;
+              return true;
             }
           }
           if (redo = move_to(FC_DOWN))
@@ -3578,7 +3716,7 @@ bool TMSPCheck_mask::on_field_event(TOperable_field& o, TField_event e, long jol
     }
     set(FC_MOVEFILTER,old_movefilter);
   }
-  return TRUE;
+  return true;
 }
 
 int TMSPCheck_mask::find_constr_row(int row)
@@ -3610,7 +3748,7 @@ bool TMSPCheck_mask::move_to(int dlg)
 
   CHECK(constraints||articles, "N'do cazzo muovo?");
   const int max_rows=_sheet->items();
-  bool skip_row=TRUE;
+  bool skip_row=true;
   int old_row=_row;
   switch (dlg)
   {
@@ -3649,8 +3787,8 @@ bool TMSPCheck_mask::move_to(int dlg)
     _row=old_row;
   check_pos_range();
   if (_last_col==_col && _last_row==_row)
-    return FALSE;
-  return TRUE;
+    return false;
+  return true;
 }
 
 void TMSPCheck_mask::check_pos_range()
@@ -3744,7 +3882,7 @@ int TCRPCheck_mask::fill_mask(const bool show_fields)
   data_buck += (_main_mask->days_per_bucket())*(_col-1);
   _main_mask->round_date(data_buck);
   set(FC_DATE1,data_buck.string());
-  _main_mask->round_date(data_buck,TRUE);
+  _main_mask->round_date(data_buck,true);
   set(FC_DATE2,data_buck.string());
 
   set(FC_IS_VINCOLO,is_constr ? "X" : " ");
@@ -3786,11 +3924,12 @@ int TCRPCheck_mask::fill_mask(const bool show_fields)
 
 void TPlanning_app ::openfiles()
 {
-    open_files(LF_TABCOM, LF_TAB, LF_DOC, LF_RIGHEDOC, 0);
-    open_files(LF_CLIFO, LF_CFVEN, LF_OCCAS, LF_INDSP, LF_CONDV, 0);
-    open_files(LF_MAG, LF_MOVMAG, LF_RMOVMAG,  0);
-    open_files(LF_ANAMAG, LF_DIST, LF_RDIST, LF_MRPREPORT, 0);
+  open_files(LF_TABCOM, LF_TAB, LF_DOC, LF_RIGHEDOC, 0);
+  open_files(LF_CLIFO, LF_CFVEN, LF_OCCAS, LF_INDSP, LF_CONDV, 0);
+  open_files(LF_MAG, LF_MOVMAG, LF_RMOVMAG,  0);
+  open_files(LF_ANAMAG, LF_DIST, LF_RDIST, LF_MRPREPORT, 0);
 }
+
 bool TPlanning_app ::create()
 {
   openfiles();
@@ -3828,4 +3967,6 @@ int mr2200(int argc, char* argv[])
   TPlanning_app a;
   a.run(argc, argv, TR("Pianificazione ordini"));
   return 0;
-}
\ No newline at end of file
+}
+
+
diff --git a/mr/mr2200.h b/mr/mr2200.h
index 6f2c0df25..bc722baf5 100755
--- a/mr/mr2200.h
+++ b/mr/mr2200.h
@@ -2,11 +2,7 @@
 #define __MR2200_H
 
 #include <applicat.h>
-#include <colmask.h>
 #include "mrplib.h"
-#include "../mg/mglib.h"
-#include "../ve/velib.h"
-#include "../ve/veconf.h"
 
 #include "mr2100.h"
 #include "mr2201.h"
diff --git a/mr/mr2200a.h b/mr/mr2200a.h
index 1e5b459b5..556c11970 100755
--- a/mr/mr2200a.h
+++ b/mr/mr2200a.h
@@ -55,11 +55,11 @@
 #define F_USENONSTDLIN_MSP 230
 #define F_USEEXTRAHRS_MSP  231
 #define F_HUMANCHECK_MSP   232
-//#define F_???            233
-//#define F_???            234
+#define F_NOANTICIPI_MSP   233
+#define F_RIFERIMENTO_MSP  234
 //#define F_???            235
 #define F_RECALC_TYPE      236
-//#define F_???            237
+#define F_PRIORITY         237
 #define F_LOTSIZING        238
 #define F_ANTICIPOMAX      239
 #define F_ANTICIPOMIN      240
@@ -93,6 +93,9 @@
 #define F_FRSGM            264
 #define F_TOGRM            265
 #define F_TOSGM            266
+#define F_IMP              267
+#define F_IGNORE_PREC      268
+
 
 // filtri di salvataggio
 #define F_SAVE_OPT         260
diff --git a/mr/mr2200a.uml b/mr/mr2200a.uml
index a48135ab5..e1f36dd52 100755
--- a/mr/mr2200a.uml
+++ b/mr/mr2200a.uml
@@ -304,6 +304,18 @@ BEGIN
   CHECKTYPE NORMAL
 END
 
+STRING F_IMP 5
+BEGIN
+  PROMPT 2 19 "Impianto    "
+  FLAG "UZ"
+  USE IMP
+  INPUT CODTAB F_IMP
+  DISPLAY "Codice@5" CODTAB
+  DISPLAY "Descrizione@60" S0
+  OUTPUT F_IMP CODTAB
+  CHECKTYPE NORMAL
+END
+
 ENDPAGE
 
 PAGE "Elabora"  -1 -1 80 19 
@@ -463,18 +475,23 @@ BEGIN
   CHECKTYPE REQUIRED
 END
 
+BOOLEAN F_IGNORE_PREC
+BEGIN
+  PROMPT 2 18 "Ignora le pianificazioni precedenti alla data iniziale"
+END
+
 ENDPAGE
 
-
 PAGE "Genera"  -1 -1 78 20
-GROUPBOX DLG_NULL 78 7
+
+GROUPBOX DLG_NULL 78 8
 BEGIN
-  PROMPT 1 1 "@b Ricalcolo" 
+  PROMPT 1 0 "@b Ricalcolo" 
 END
 
 LIST F_RECALC_TYPE 35
 BEGIN
-  PROMPT 2 2 "Logica propositiva "
+  PROMPT 2 1 "Logica propositiva "
 #ifndef _IS_ACQ
   ITEM       "1|FirstFit                     "
     MESSAGE ENABLE,G_FINITE@
@@ -511,6 +528,11 @@ BEGIN
     MESSAGE COPY,F_RECALC_TYPE2
 END
 
+STRING F_PRIORITY 60
+BEGIN
+  PROMPT 2 2 "Priorita' "
+END
+
 BOOL F_LOTSIZING
 BEGIN
   PROMPT 2 3 "Ridimensiona in base ai lotti"
@@ -598,41 +620,53 @@ BEGIN
   PROMPT 42 10 "Abilita turni straordinari"
 END
 
-GROUPBOX DLG_NULL 78 18
+BOOL F_NOANTICIPI_MSP
 BEGIN
-  PROMPT 1 11 "@b Registrazione" 
+  PROMPT 2 11 "Non anticipare gli articoli con distinta"
+END
+
+LIST F_RIFERIMENTO_MSP 1 20
+BEGIN
+  PROMPT 32 11 "Riferimento sulle righe "
+  ITEM "0|Documento originale"
+  ITEM "1|Documento padre"
+END
+
+GROUPBOX DLG_NULL 78
+BEGIN
+  PROMPT 1 12 "@b Registrazione" 
 END
 
 BOOLEAN F_NUMBERBYWEEK
 BEGIN
-  PROMPT 2 12  "Numera gli ordini per settimana"
+  PROMPT 2 13  "Numera gli ordini per settimana"
   GROUP G_PREPROCESS
   MESSAGE TRUE "X",F_DIVIDEBYDATE
 END
 
 BOOLEAN F_NUMBERBYCLI
 BEGIN
-  PROMPT 40 12  "Numera gli ordini per cliente"
+  PROMPT 40 13  "Numera gli ordini per cliente"
   GROUP G_PREPROCESS
 END
 
 
 BOOLEAN F_DIVIDEBYART
 BEGIN
-  PROMPT 2 13  "Suddividi gli ordini per articolo"
+  PROMPT 2 14  "Suddividi gli ordini per articolo"
   GROUP G_PREPROCESS
 END
 
 BOOLEAN F_DIVIDEBYDATE
 BEGIN
-  PROMPT 40 13  "Suddividi gli ordini per scadenza"
+  PROMPT 40 14  "Suddividi gli ordini per scadenza"
   GROUP G_PREPROCESS
 END
 
 
 SPREADSHEET F_SAVE_OPT 70 -1
 BEGIN
-  PROMPT 2 14 ""
+  PROMPT 2 15 ""
   ITEM " "
   ITEM "Num.@6"
   ITEM "Tipo@6"
diff --git a/mr/mr2201.cpp b/mr/mr2201.cpp
index 76fa7a74e..11c28ac8a 100755
--- a/mr/mr2201.cpp
+++ b/mr/mr2201.cpp
@@ -1,7 +1,9 @@
 #include <execp.h>
-#include "mrplib.h"
+#include <printer.h>
+#include <progind.h>
+#include <utility.h>
+
 #include "../mg/mglib.h"
-#include "../ve/velib.h"
 #include "../ve/veconf.h"
 
 #include "mr2100.h"
@@ -14,8 +16,8 @@ static TDistinta_tree *_dist_tree=NULL;
 
 TDistinta_tree &dist_tree()
 {
-  if (!_dist_tree)
-    _dist_tree=new TDistinta_tree();
+  if (_dist_tree == NULL)
+    _dist_tree = new TDistinta_tree();
   return *_dist_tree;
 }
 
@@ -23,7 +25,7 @@ TDistinta_tree &dist_tree()
 // triga ordine
 ///////////////////////////////////////////////////////////
 
-TMSP_form::TMSP_form (TIsamtempfile * report) :TForm("mr2200a")
+TMSP_form::TMSP_form (TIsamtempfile * report) : TForm("mr2200a")
 {
   TRelation* rel = relation();
   rel->replace(report);
@@ -791,7 +793,10 @@ void TMSP_constraint::fill_sheet_row(TToken_string& row, const TMask & m, bool c
 
   row.add(format("%ld", codclifor()),F_CLIENTE-FIRST_FIELD);
   row.add(articolo(),F_ARTICOLO-FIRST_FIELD);
-  row.add(" ",F_PRIORITA-FIRST_FIELD);
+  if (_priority != 0)
+    row.add(_priority, F_PRIORITA-FIRST_FIELD);
+  else
+    row.add(" ",F_PRIORITA-FIRST_FIELD);
 
   const TString& liv = livgiac();  
   for (int l = 1; l <= 4; l++)
@@ -856,11 +861,13 @@ const char *TMSP_constraint::um()
   key.add("1");
   return cache().get(LF_UMART,key).get("UM");
 }
-void TMSP_constraint::add_rigaref(int buck, TString& codnum, int annodoc, long ndoc, int nrig, const char * um, const real & qta, const real &prz)
+
+TMRP_docref* TMSP_constraint::add_rigaref(int buck, TString& codnum, int annodoc, long ndoc, int nrig, const char * um, const real & qta, const real &prz)
 {
   TMSP_record& b = _bucket_qta[buck];
   TMRP_docref *rdr= new TMRP_docref(annodoc, codnum, ndoc, nrig, um, qta,prz);
   b.add_rigaref(rdr);
+  return rdr;
 }
 
 void TMSP_constraint::add_rigaref(int buck, TMRP_docref *rdr)
@@ -877,13 +884,13 @@ void TMSP_constraint::remove_rigaref(int buck)
 
 int TMSP_constraint::find_distinta_master(const TMSP_constraint & constr, TString & master,TString & livmaster,TString & um, real & expr, TString & imp,TString & lin,TString & magdep, int fromindex)
 {
-  TArray sons;
   dist_tree().set_global("_LIVELLO",constr.livgiac());
   dist_tree().set_global("_IMPIANTO",constr.codimp());
   dist_tree().set_global("_LINEA",constr.codlin());
   dist_tree().set_global("_MAGDEP",constr.codmagdep());
   if (dist_tree().set_root(constr.articolo()))
   {
+    TArray sons;
     dist_tree().explode(sons, FALSE, RAGGR_EXP_NONE, 1, "AV");
     TRiga_esplosione* riga;
     while (riga=(TRiga_esplosione* )sons.objptr(fromindex))
@@ -899,7 +906,7 @@ int TMSP_constraint::find_distinta_master(const TMSP_constraint & constr, TStrin
       fromindex=sons.succ(fromindex);
     }
   }
-  master="";
+  master.cut(0);
   return -1;
 }
 
@@ -1076,14 +1083,14 @@ TMSP_constraint::TMSP_constraint(long cliente,
                                  const TString& mag,
                                  const TString& magc)
 : _codclifor(cliente), _codart(codart), _livgiac(giac), 
-  _codimp(imp), _codlin(lin), _codmag(mag), _codmag_coll(magc),_on_sheet(FALSE),_check_master(FALSE), _upperlines(NULL), _lines2(NULL)
+  _codimp(imp), _codlin(lin), _codmag(mag), _codmag_coll(magc),_on_sheet(FALSE),_check_master(FALSE), _upperlines(NULL), _lines2(NULL), _priority(0)
 
 { }
 
 TMSP_constraint::TMSP_constraint(const TMSP_constraint & line)
 : _codclifor(line.codclifor()), _codart(line.articolo()), _livgiac(line.livgiac()), 
   _codimp(line.codimp()), _codlin(line.codlin()), _codmag(line.codmagdep()), _codmag_coll(line.codmagdep_coll()),
-  _descr(line.description()), _on_sheet(FALSE), _check_master(FALSE), _upperlines(NULL), _lines2(NULL)
+  _descr(line.description()), _on_sheet(FALSE), _check_master(FALSE), _upperlines(NULL), _lines2(NULL), _priority(0)
 {
 }
 
@@ -1472,7 +1479,7 @@ bool TLista_dettagli::bucket_handler(TMask_field & f, KEY key)
   return TRUE;
 }
 
-void TLista_dettagli::init(const char * title, TDate fromdate, int bucketsize)
+void TLista_dettagli::init(const char * title, const TDate& fromdate, int bucketsize)
 {
   _curr_bucket = -1;
   _from = fromdate;
@@ -1484,7 +1491,7 @@ void TLista_dettagli::init(const char * title, TDate fromdate, int bucketsize)
   add_string(FIRST_FIELD+3,0,TR("Settimana "),49,0,15,"D");
 }
 
-TLista_dettagli::TLista_dettagli(const char * title, TDate fromdate, int bucketsize, const char * head) : 
+TLista_dettagli::TLista_dettagli(const char * title, const TDate& fromdate, int bucketsize, const char * head) : 
   TSheet(-1, 5, 80, 15, title, head,0,2)
 {
   init(title, fromdate, bucketsize); 
@@ -1493,26 +1500,21 @@ TLista_dettagli::TLista_dettagli(const char * title, TDate fromdate, int buckets
 
 void TLista_docref::get_row(long r, TToken_string& row) 
 { 
-  row = "";
+  row.cut(0);
   if (r < _line->rigarefs(curr_bucket()))
   {
     TMRP_docref * rdr=_line->rigaref(curr_bucket(),(int)r);
     if (rdr)
     {
-      TLocalisamfile & rdoc = _r->lfile(LF_RIGHEDOC);
-      TLocalisamfile & doc = _r->lfile(LF_DOC);
-      rdoc.put(RDOC_PROVV,"D");
-      rdoc.put(RDOC_ANNO,rdr->annodoc());
-      rdoc.put(RDOC_CODNUM,rdr->codnumdoc());
-      rdoc.put(RDOC_NDOC,rdr->numdoc());
-      rdoc.put(RDOC_NRIGA,rdr->numrig());
-      _r->read();
+      const TRectype& doc = rdr->get_doc();
+      const TRectype& rdoc = rdr->get_rdoc();
+
       row.add(" ");
       row.add(rdr->annodoc());
       row.add(rdr->codnumdoc());
       row.add(rdr->numdoc());
       row.add(rdr->numrig());
-      TDate dc(rdoc.get_date(RDOC_DATACONS));
+      const TDate dc(rdoc.get(RDOC_DATACONS));
       row.add(dc.ok() ? dc : doc.get_date(RDOC_DATACONS));
       row.add(rdoc.get(RDOC_UMQTA));
       real q(rdoc.get_real(RDOC_QTA));
@@ -1521,6 +1523,9 @@ void TLista_docref::get_row(long r, TToken_string& row)
       row.add(q.string("#######@,@@@"));
       //const char statodef=cache().get("%TIP",doc.get(DOC_TIPODOC)).get("S2")[1];
       row.add(doc.get(DOC_STATO));
+      row.add(rdoc.get(RDOC_DAANNO));
+      row.add(rdoc.get(RDOC_DACODNUM));
+      row.add(rdoc.get(RDOC_DANDOC));
       enable_row(r);
     }
   } 
@@ -1569,9 +1574,9 @@ long TLista_docref::get_items(int b) const
 }
 
 
-TLista_docref::TLista_docref(TMSP_constraint * l, const char * title, TDate fromdate, int bucketsize) : 
-  TLista_dettagli(title, fromdate, bucketsize,
-         "@1|Anno|CodNum|Numero|Riga|Consegna@10|UM|Q.ta totale@12|Q.ta residua@12|Stato"),
+TLista_docref::TLista_docref(TMSP_constraint * l, const char * title, TDate fromdate, int bucketsize) 
+             : TLista_dettagli(title, fromdate, bucketsize,
+         "@1|Anno|CodNum|Numero|Riga|Consegna@10|UM|Q.ta totale@12|Q.ta residua@12|Stato|Da Anno|Da CodNum|Da NDoc"),
          _line (l)
 {
   _r= new TRelation(LF_RIGHEDOC);
diff --git a/mr/mr2201.h b/mr/mr2201.h
index 024039425..c451de5bb 100755
--- a/mr/mr2201.h
+++ b/mr/mr2201.h
@@ -1,13 +1,9 @@
 #ifndef __MR2201_H
 #define __MR2201_H
-#include <colors.h>
-#include <defmask.h>
-#include <progind.h>
-#include <tabutil.h>
-#include <xvtility.h>
-#include <utility.h>
-#include <printer.h>
+
+#ifndef __SHEET_H
 #include <sheet.h>
+#endif
 
 // funzioni di ricerca distinta master
 bool distinta_master(const char *code, bool is_son=FALSE);
@@ -186,13 +182,14 @@ class TMSP_constraint : public TSortable
   long _codclifor;             // cliente o fornitore
   TCodice_articolo _codart;    // articolo
   TString16 _livgiac;          // livelli di giacenza
-  TString8 _codmag;            // magazzino /deposito
-  TString8 _codmag_coll;       // magazzino /deposito collegato
-  TString8 _codimp, _codlin;   // codice impianto e linea
+  TString8 _codmag;            // magazzino/deposito
+  TString8 _codmag_coll;       // magazzino/deposito collegato
+  TString8 _codimp, _codlin;   // codici impianto e linea
   TString _descr;              // descrizione
+  long _priority;
   
   bool _on_sheet;               // gia' sullo sheet
-  bool _check_master;           // anrticolo non master, controllare se esistono Master
+  bool _check_master;           // articolo non master, controllare se esistono Master
   TArray           *_lines2;     // codici master per articoli NON master
   TMSP_constraints *_upperlines; // vincoli dei codici di livello 1 per articoli master
 
@@ -224,7 +221,7 @@ public:
   TMRP_docref * next_rigaref(int buck);
   int rigarefs(int buck);
   TMRP_docref* rigaref(int buck, int n);
-  void add_rigaref(int buck, TString& codnum, int annodoc, long ndoc, int nrig, const char * um, const real & qta, const real &prz);
+  TMRP_docref* add_rigaref(int buck, TString& codnum, int annodoc, long ndoc, int nrig, const char * um, const real & qta, const real &prz);
   void add_rigaref(int buck, TMRP_docref *rdr);
   void remove_rigaref(int buck);
   // master sched. a due livelli:
@@ -252,6 +249,9 @@ public:
   virtual real& qta_min(int b)    { return _bucket_qta[b]._qta_min; } 
   virtual real& qta(int b)    { return _bucket_qta[b]._qta; } 
   virtual real& price(int b)  { return _bucket_qta[b]._price; } 
+  
+  virtual long priority() const { return _priority; }
+  virtual void priority(long p) { _priority = p; }
 
   virtual void fill_sheet_row(TToken_string& row, const TMask & m, bool codes_only=FALSE) ;
 
@@ -441,8 +441,8 @@ public:
   bool reset_bucket_field();
   int  curr_bucket() const {return _curr_bucket;}
   void set_bucket(int b);
-  void init(const char * title, TDate fromdate, int bucketsize);
-  TLista_dettagli(const char * title, TDate fromdate, int bucketsize, const char * head);
+  void init(const char * title, const TDate& fromdate, int bucketsize);
+  TLista_dettagli(const char * title, const TDate& fromdate, int bucketsize, const char * head);
   ~TLista_dettagli() {}
 };
 
diff --git a/mr/mr2202.cpp b/mr/mr2202.cpp
index b2ec74628..beaa65850 100755
--- a/mr/mr2202.cpp
+++ b/mr/mr2202.cpp
@@ -1,3 +1,7 @@
+#include <printer.h>
+#include <progind.h>
+#include <utility.h>
+
 #include "mr2200.h"
 #include "mr2200a.h"
 #include "mr2200b.h"
diff --git a/mr/mrplib.cpp b/mr/mrplib.cpp
index 2bafc760a..023efc8b4 100755
--- a/mr/mrplib.cpp
+++ b/mr/mrplib.cpp
@@ -18,14 +18,17 @@ TAssoc_array TMRP_time::_frate_indovino;
 TMRP_calendar& TMRP_time::get_calendar(const char* codimp,const char* codlin)
 {
   TToken_string k;
-  k.add(codimp);
-  k.add(codlin);
+  k = codimp; k.add(codlin);
   TMRP_calendar* cal = (TMRP_calendar*)_frate_indovino.objptr(k);
   if (cal == NULL)
   {
-    if (_frate_indovino.items() > 16) 
-      _frate_indovino.destroy(); // troppi calendari fanno male alla salute...
-    
+    if (_frate_indovino.items() > 64) // troppi calendari fanno male alla salute...
+    {
+      // _frate_indovino.destroy(); // Esagerato: cancella tutto
+      const THash_object* rnd = _frate_indovino.random_hash_object();
+      if (rnd != NULL)
+        _frate_indovino.remove(rnd->key()); // Cancella uno a caso
+    }
     cal = new TMRP_calendar(codlin, codimp);
     _frate_indovino.add(k, cal);
   }
@@ -50,7 +53,7 @@ int TMRP_time::compare(const TSortable& s) const
 
 TMRP_time& TMRP_time::add_time(int days, long hours,bool macchina)
 {
-  TMRP_calendar& cal = calendario();
+  const TMRP_calendar& cal = calendario();
   if (days != 0)
   {
     cal.next_working_day(_date, days);
@@ -73,7 +76,7 @@ TMRP_time& TMRP_time::add_time(int days, long hours,bool macchina)
       {
         cal.prev_working_day(_date);
         hours += _hour;
-        _hour = (macchina ? cal.add_oremacchina(junk, _date) : cal.add_oreuomo(junk,_date));
+        _hour = macchina ? cal.add_oremacchina(junk, _date) : cal.add_oreuomo(junk,_date);
       }
     }
     else
@@ -153,7 +156,7 @@ long TMRP_array::sort()
 
   TProgind* pi = NULL;
   if (last >= 16)
-    pi = new TProgind(last, TR("Ordinamento"), FALSE, TRUE);
+    pi = new TProgind(last, TR("Ordinamento"), false, true);
   else
     begin_wait();
 
@@ -161,10 +164,10 @@ long TMRP_array::sort()
   {
     if (pi) pi->addstatus(1);
     TSortable* best = &find_obj(i);
-    bool swapped = TRUE;
+    bool swapped = true;
     while (swapped)
     {
-      swapped = FALSE;
+      swapped = false;
       for (long j = i+1; j <= last; j++)
       {
         TSortable& other = find_obj(j);
@@ -172,9 +175,9 @@ long TMRP_array::sort()
         {
 //          swap(i, j);
 //          best = &other;
-          best = (TSortable*)_by_idx.remove(int(j), TRUE);
+          best = (TSortable*)_by_idx.remove(int(j), true);
           _by_idx.TArray::insert(best, int(i));
-          swapped = TRUE; 
+          swapped = true; 
         }
       }
     }
@@ -207,10 +210,10 @@ void TMRP_calendar::init_default()
   // Inizializza i turni dei 5 giorni feriali a 1
   // Inizializza i turni di sabato e domenica a 0
   // Inizializza i turni dei giorni festivi   a 0
-  _days = cfg.get(TR("Turni"), NULL, -1, "1111100011111000");
+  _days = cfg.get("Turni", NULL, -1, "1111100011111000");
   // Inizializza la lista delle feste comandate tranne la Pasqua
-  _holidays = cfg.get(TR("Feste"), NULL, -1, 
-                      "01-01|06-01|25-04|01-05|15-08|01-11|08-12|25-12|26-12");
+  _holidays = cfg.get("Feste", NULL, -1, 
+                      "01-01|06-01|25-04|01-05|02-06|15-08|01-11|08-12|25-12|26-12");
   TUnita_produttiva * up=NULL;
   if (_codlin.not_empty())
     up=new TLinea_prod(_codlin);
@@ -252,7 +255,7 @@ bool TMRP_calendar::is_holiday(const TDate& date) const
 bool TMRP_calendar::is_red(const TDate& date) const
 {
   if (date.wday() == 7)
-    return TRUE;
+    return true;
   return is_holiday(date);
 }
 
@@ -353,19 +356,21 @@ int TMRP_calendar::remove_cal(const TString& code, char tipo) const
   return NOERR;
 }
 
-int TMRP_calendar::turni(const TDate& data, int& mini, int& maxi, bool as_is)
+int TMRP_calendar::turni(const TDate& data, int& mini, int& maxi, bool as_is) const
 {
   const int year  = data.year();
   const int month = data.month();
   const int day   = data.day(); 
   TString16 str;
 
+  TMRP_calendar& myself = (TMRP_calendar&)*this;
+
   mini = maxi = -1;
   if (_codlin.not_empty())
   {
     str.format("%04d%02d", year, month);
     if (_exc_lin.objptr(str) == NULL)
-      read_cal(str, 'L');
+      myself.read_cal(str, 'L');
 
     const TString& turn = (const TString&)_exc_lin[str];
     mini = turn[day-1] - '0';
@@ -378,7 +383,7 @@ int TMRP_calendar::turni(const TDate& data, int& mini, int& maxi, bool as_is)
   {
     str.format("%04d%02d", year, month);
     if (_exc_imp.objptr(str) == NULL)
-      read_cal(str, 'I');
+      myself.read_cal(str, 'I');
 
     const TString& turn = (const TString&)_exc_imp[str];
     mini = turn[day-1] - '0';
@@ -389,7 +394,7 @@ int TMRP_calendar::turni(const TDate& data, int& mini, int& maxi, bool as_is)
   }
 
   if (_days.empty())
-    init_default();
+    myself.init_default();
 
   // Controlla se e' festa
   for (str = _holidays.get(0); str.not_empty(); str = _holidays.get())
@@ -498,7 +503,7 @@ int TMRP_calendar::set_turni(const TDate& data, int mini, int maxi)
   return 0;
 }
 
-int TMRP_calendar::add_oreuomo(real & var,const TDate& date, bool max)
+int TMRP_calendar::add_oreuomo(real & var,const TDate& date, bool max) const
 {
   long minuti = 0L;
   const int tm = max ? turni_max(date) : turni_min(date);
@@ -509,12 +514,12 @@ int TMRP_calendar::add_oreuomo(real & var,const TDate& date, bool max)
   return ore;
 }
 
-int TMRP_calendar::add_oreuomo_max(real & var,const TDate& date)
+int TMRP_calendar::add_oreuomo_max(real & var,const TDate& date) const
 {
-  return add_oreuomo(var, date,TRUE);
+  return add_oreuomo(var, date,true);
 }
 
-int TMRP_calendar::add_oremacchina(real & var,const TDate& date, bool max)
+int TMRP_calendar::add_oremacchina(real & var,const TDate& date, bool max) const
 {
   const int tm = max ? turni_max(date) : turni_min(date);
   real minuti(ZERO);
@@ -552,9 +557,9 @@ int TMRP_calendar::add_oremacchina(real & var,const TDate& date, bool max)
   return int(minuti.integer());
 }
 
-int TMRP_calendar::add_oremacchina_max(real & var,const TDate& date)
+int TMRP_calendar::add_oremacchina_max(real & var,const TDate& date) const
 {
-  return add_oremacchina(var, date,TRUE);
+  return add_oremacchina(var, date, true);
 }
 
 int TMRP_calendar::write() const
@@ -613,7 +618,7 @@ char TMRP_calendar::tipo() const
   return 'S';
 }
 
-TDate& TMRP_calendar::next_working_day(TDate& work, int gap)
+TDate& TMRP_calendar::next_working_day(TDate& work, int gap) const
 {
   const int delta = gap >= 0 ? +1 : -1;
   const int steps = gap >= 0 ? gap : -gap;
@@ -694,7 +699,9 @@ void TCalendar_win::handler(WINDOW win, EVENT* ep)
           {
             m.add_list(104, 0, TR("Turni minimi  "), 1, 4, 8, "", "0|1|2|3|4|5|6|7|8", "Nessuno|1 turno|2 turni|3 turni|4 turni|5 turni|6 turni|7 turni|8 turni");
             m.add_list(105, 0, TR("Turni massimi "), 1, 5, 8, "", "0|1|2|3|4|5|6|7|8", "Nessuno|1 turno|2 turni|3 turni|4 turni|5 turni|6 turni|7 turni|8 turni");
-          } else {
+          } 
+          else 
+          {
             m.add_list(104, 0, TR("Turni minimi  "), 1, 4, 8, "", " |0|1|2|3|4|5|6|7|8", "Standard|Nessuno|1 turno|2 turni|3 turni|4 turni|5 turni|6 turni|7 turni|8 turni");
             m.add_list(105, 0, TR("Turni massimi "), 1, 5, 8, "", " |0|1|2|3|4|5|6|7|8", "Standard|Nessuno|1 turno|2 turni|3 turni|4 turni|5 turni|6 turni|7 turni|8 turni");
           }
@@ -709,7 +716,7 @@ void TCalendar_win::handler(WINDOW win, EVENT* ep)
           m.set(102, itow(d.wday()));
           m.set(103, festa ? "X" : "");
           int mini, maxi; 
-          _calendario->turni(d, mini, maxi, TRUE);
+          _calendario->turni(d, mini, maxi, true);
           m.set(104, mini);
           m.set(105, maxi);
           _calendario->turni(d, mini, maxi, FALSE);
@@ -764,7 +771,7 @@ void TCalendar_win::update()
     bmp.draw(win(), x, y);
   }
 
-  _pixmap = TRUE;
+  _pixmap = true;
 
   TString16 str;
   str << _anno;
@@ -1057,12 +1064,12 @@ void TMRP_config::set_durata_turno(int i,int ore, int minuti)
 
 void TMRP_config::set_inizio_turno(int i,int time)
 {
-  set("TINIZIO", time, "mr", TRUE, i);
+  set("TINIZIO", time, "mr", true, i);
 }
 
 void TMRP_config::set_durata_turno(int i,int time)
 {
-  set("TDURATA", time, "mr", TRUE, i);
+  set("TDURATA", time, "mr", true, i);
 }
 
 //********
@@ -1352,7 +1359,7 @@ void find_price(const TString &tipocv, const TString &codcv, const TString &codc
 {
   static TCondizione_vendita *_condv =NULL;
 
-  bool retry=TRUE;
+  bool retry=true;
   if (_condv == NULL)
     _condv = new TCondizione_vendita(new TConfig (CONFIG_DITTA));
 
@@ -1380,4 +1387,171 @@ void find_price(const TString &tipocv, const TString &codcv, const TString &codc
   } 
 }
 
+void TProduzione::init()
+{
+  add_file(LF_RRILPROD, "NRIGA");
+}
+
+TProduzione::TProduzione()
+           : TMultiple_rectype(LF_RILPROD)
+{                      
+  init();
+}
+
+TProduzione::TProduzione(const TProduzione & d)
+           : TMultiple_rectype(LF_RILPROD)
+{                                                                             
+  init();
+  copy(d);
+}
+
+TProduzione::TProduzione(const char* codart, TDate datacons, int prog)
+          : TMultiple_rectype(LF_RILPROD)
+{
+  init();
+  if (prog <= 0)
+  { 
+    prog = 0;
+    set_key(*this, codart, datacons, prog);
+  }
+  else
+    read_art(codart, datacons, prog);
+}
+
+// Funzione statica utile a tutti gli utenti di LF_DOC e LF_RIGHEDOC
+void TProduzione::set_key(TRectype& rec, const char* codart, TDate datacons, int prog)
+{
+  CHECK(codart && *codart, "Codice articolo nullo");
+  CHECK(datacons.ok(), "Data di consegna non valida ");
+
+  rec.put("CODART",  codart); 
+  rec.put("DATA", datacons);  
+  rec.put("PROG",   prog);
+}
+
+bool TProduzione::renum()
+{
+  TLocalisamfile f(LF_RILPROD);
+  TRectype& cmp = head();
+	int n = 0;
+	
+  f.curr() = cmp;
+	f.put("PROG", 999);
+
+  const int err = f.read(_isgreat);
+              
+  if (err != _isemptyfile)
+  {
+    if (err == NOERR)
+      f.prev();
+    if (f.get("CODART") == cmp.get("CODART") && 
+        f.get("DATA") == cmp.get_date("DATA"))
+       n = f.get_int("PROG");
+  }     
+	cmp.put("PROG", n + 1);
+	return true;
+}
+
+int TProduzione::read_art(const char* codart, TDate datacons, int prog, word op, word lockop)
+{                           
+	TLocalisamfile f(LF_RILPROD);
+
+  zero();
+  set_key(*this, codart, datacons, prog);
+	if (prog == 0)
+	{
+	  TRectype& cmp = head();
+	
+	  f.curr() = cmp;
+		f.put("PROG", 999);
+
+	  const int err = f.read(_isgreat);
+              
+	  if (err != _isemptyfile)
+	  {
+	    if (err == NOERR)
+				f.prev();
+			if (f.get("CODART") == cmp.get("CODART") && 
+					f.get("DATA") == cmp.get_date("DATA"))
+				 cmp.put("PROG", f.get("PROG"));
+			else
+				return _iskeynotfound;
+		}     
+		else
+			return _iskeynotfound;
+	}
+  return TMultiple_rectype::read(f, op, lockop);
+}
+
+int TProduzione::read_ordp(const char* codnum, int anno, char provv, long ndoc, int nriga, word op, word lockop)
+{
+	TLocalisamfile f(LF_RILPROD);
+
+	f.setkey(4);
+	f.put("CODNUM", codnum);
+	f.put("ANNO", anno);
+	f.put("PROVV", "D");
+	f.put("NDOC", ndoc);
+	f.put("NRIGA", nriga);
+
+	int err = f.read();
+
+	head() = f.curr();
+	f.setkey(1);
+	if (err == NOERR)
+		err = TMultiple_rectype::read(f, op, lockop);
+	else
+		zero();
+	return err;
+}
+
+int TProduzione::read_bolp(const char* codnum, int anno, char provv, long ndoc, int nriga, word op, word lockop)
+{
+	TLocalisamfile f(LF_RILPROD);
+
+	f.setkey(5);
+	f.put("CODNUM", codnum);
+	f.put("ANNO", anno);
+	f.put("PROVV", "D");
+	f.put("NDOC", ndoc);
+	f.put("NRIGA", nriga);
+
+	int err = f.read();
+	
+	head() = f.curr();
+	f.setkey(1);
+	if (err == NOERR)
+		err = TMultiple_rectype::read(f, op, lockop);
+	else
+		zero();
+	return err;
+}
+
+void TProduzione::copy_data(TRectype& dst, const TRectype& src)
+{                           
+  // Memorizza tutti i campi chiave
+  const TString codart  = dst.get("CODART");  
+  const TDate datacons  = dst.get_date("DATA");  
+  const int prog        = dst.get_int("PROG");  
+  const int nriga       = dst.num() == LF_RRILPROD ? dst.get_int("NRIGA") : 0;
+  // Copia tutto il record     
+  dst = src;                          
+  // Ripristina tutti i campi chiave
+  set_key(dst, codart, datacons, prog);
+  if (nriga > 0)
+    dst.put("NRIGA", nriga);
+}
+
+void TProduzione::copy_contents(const TProduzione& src)
+{
+  copy_data(head(), src.head()); 
+  destroy_rows();  
+  const int rows = src.rows(); 
+  for (int i = 1; i <= rows ; i++)
+  {
+    const TRectype & s = src.body()[i];
+    TRectype & r = new_row();
+    copy_data(r, s);
+  }
+}
 
diff --git a/mr/mrplib.h b/mr/mrplib.h
index ac9c1b992..9448fbb94 100755
--- a/mr/mrplib.h
+++ b/mr/mrplib.h
@@ -38,7 +38,7 @@ public:
   long items() const { return _by_key.items(); }
   void destroy();
   long sort();
-  void add(TMRP_array &a, bool force=FALSE);
+  void add(TMRP_array &a, bool force=false);
 
   // I metodi add(), find() e operator[] devono essere dichiarati
   // dalle classi derivate e ritornare i tipi giusti tramite cast
@@ -64,7 +64,7 @@ class TMRP_calendar : public TObject
   int _persturno[8];
 
   TAssoc_array _exc_imp, _exc_lin;
-  TString16 _codimp, _codlin;
+  TString8 _codimp, _codlin;
 
 protected:
   void init_default();
@@ -73,23 +73,23 @@ protected:
   int remove_cal(const TString& code, char tipo) const;
 
 public:
-  int turni(const TDate& date, int& mini, int& maxi, bool as_is = FALSE);
+  int turni(const TDate& date, int& mini, int& maxi, bool as_is = false) const;
 
-  int turni_min(const TDate& date) 
+  int turni_min(const TDate& date) const
   { int mini, maxi; turni(date, mini, maxi); return mini; }
   
-  int turni_max(const TDate& date) 
+  int turni_max(const TDate& date) const
   { int mini, maxi; turni(date, mini, maxi); return maxi; }
 
   // ore minime e massime ad una certa data
-  int add_oremacchina(real & var,const TDate& date, bool max=FALSE);
-  int add_oremacchina_max(real & var,const TDate& date);
+  int add_oremacchina(real & var,const TDate& date, bool max=false) const;
+  int add_oremacchina_max(real & var,const TDate& date) const;
 
-  int add_oreuomo(real & var,const TDate& date, bool max=FALSE);
-  int add_oreuomo_max(real & var,const TDate& date);
+  int add_oreuomo(real & var,const TDate& date, bool max=false) const;
+  int add_oreuomo_max(real & var,const TDate& date) const;
 
-  TDate& next_working_day(TDate& from, int gap = 1);
-  TDate& prev_working_day(TDate& from, int gap = 1)
+  TDate& next_working_day(TDate& from, int gap = 1) const;
+  TDate& prev_working_day(TDate& from, int gap = 1) const
   { return next_working_day(from, -gap); }
   
   int set_turni(const TDate& date, int mini, int maxi);
@@ -172,7 +172,6 @@ public:
 
   void set(const TDate& d, int h, const char* imp, const char* lin);
   TMRP_time& operator=(const TMRP_time& t) { copy(t); return *this; }
-
   
   TMRP_time();
   TMRP_time(const TDate& d, int h, const char* imp, const char* lin);
@@ -302,4 +301,31 @@ TLinea_prod* get_linea(const char * codice);
 void find_price(const TString &tipocv, const TString &codcv, const TString &codcatven, 
   const char * tipocf, long codcf, const char * codice, const real & qta, real & price);
 
+class TProduzione : public TMultiple_rectype
+{               
+
+protected:  
+	void init();
+	virtual TProduzione & copy(const TProduzione & d) { return (TProduzione &) TMultiple_rectype::operator=((TMultiple_rectype &)d);} 
+  virtual TObject* dup() const { return new TProduzione(*this); }
+  virtual bool renum();
+  virtual bool key_complete() { return head().get_int("PROG") != 0; }
+
+public:                       
+  virtual TProduzione & operator =(const TProduzione & d) {return copy(d);}
+	static void set_key(TRectype& rec, const char* codart, TDate datacons, int prog);
+  static void copy_data(TRectype & dst, const TRectype & src);
+  static void copy_row(TRectype & dst, const TRectype & src) { copy_data((TRectype&)dst, (const TRectype&)src);}
+	void copy_contents(const TProduzione & src);
+
+	int read_art(const char* codart, TDate datacons, int prog, word op = _isequal, word lockop = _nolock);
+	int read_ordp(const char* codnum, int anno, char provv, long ndoc, int nriga, word op = _isequal, word lockop = _nolock);
+	int read_bolp(const char* codnum, int anno, char provv, long ndoc, int nriga, word op = _isequal, word lockop = _nolock);
+
+  TProduzione();
+  TProduzione(const TProduzione & d);
+  TProduzione(const char* codart, TDate datacons, int prog = 0);
+  virtual ~TProduzione() {}
+ };
+
 #endif
diff --git a/projects/agalib.dsp b/projects/agalib.dsp
index 7aae43d3e..494800ace 100755
--- a/projects/agalib.dsp
+++ b/projects/agalib.dsp
@@ -45,7 +45,7 @@ AgaLib=link.exe -lib
 # ADD BASE AgaLib /nologo
 # ADD AgaLib /nologo
 # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c
-# ADD CPP /nologo /MT /W3 /O2 /I "..\xvaga" /I "..\xi" /I "..\include" /I "..\gfm" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "CB6" /YX /FD /c
+# ADD CPP /nologo /MT /W3 /O2 /I "..\xvaga" /I "..\xi" /I "..\include" /I "..\gfm" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "CB6" /FR /YX /FD /c
 # ADD BASE RSC /l 0x410
 # ADD RSC /l 0x410
 BSC32=bscmake.exe
@@ -539,6 +539,10 @@ SOURCE=..\include\sheet.h
 # End Source File
 # Begin Source File
 
+SOURCE=..\include\smartcard.h
+# End Source File
+# Begin Source File
+
 SOURCE=..\include\sort.h
 # End Source File
 # Begin Source File
diff --git a/projects/cg0.dsp b/projects/cg0.dsp
index f5ded9884..e7e5eda54 100755
--- a/projects/cg0.dsp
+++ b/projects/cg0.dsp
@@ -364,6 +364,1068 @@ InputName=cg0500a
 
 # PROP Default_Filter "h"
 # End Group
+# Begin Group "Trr"
+
+# PROP Default_Filter "trr"
+# Begin Source File
+
+SOURCE=..\cg\f103.trr
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f103.trr
+InputName=f103
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f103.trr
+InputName=f103
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f104.trr
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f104.trr
+InputName=f104
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f104.trr
+InputName=f104
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f16.trr
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f16.trr
+InputName=f16
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f16.trr
+InputName=f16
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f17.trr
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f17.trr
+InputName=f17
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f17.trr
+InputName=f17
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f18.trr
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f18.trr
+InputName=f18
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f18.trr
+InputName=f18
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f19.trr
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f19.trr
+InputName=f19
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f19.trr
+InputName=f19
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f20.trr
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f20.trr
+InputName=f20
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f20.trr
+InputName=f20
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f21.trr
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f21.trr
+InputName=f21
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f21.trr
+InputName=f21
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f22.trr
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f22.trr
+InputName=f22
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f22.trr
+InputName=f22
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f23.trr
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f23.trr
+InputName=f23
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f23.trr
+InputName=f23
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f24.trr
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f24.trr
+InputName=f24
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f24.trr
+InputName=f24
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f25.trr
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f25.trr
+InputName=f25
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f25.trr
+InputName=f25
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f26.trr
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f26.trr
+InputName=f26
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f26.trr
+InputName=f26
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f27.trr
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f27.trr
+InputName=f27
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f27.trr
+InputName=f27
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f28.trr
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f28.trr
+InputName=f28
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f28.trr
+InputName=f28
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f29.trr
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f29.trr
+InputName=f29
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f29.trr
+InputName=f29
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f30.trr
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f30.trr
+InputName=f30
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f30.trr
+InputName=f30
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# End Group
+# Begin Group "Dir"
+
+# PROP Default_Filter "dir"
+# Begin Source File
+
+SOURCE=..\cg\f103.dir
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f103.dir
+InputName=f103
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f103.dir
+InputName=f103
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f104.dir
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f104.dir
+InputName=f104
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f104.dir
+InputName=f104
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f16.dir
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f16.dir
+InputName=f16
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f16.dir
+InputName=f16
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f17.dir
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f17.dir
+InputName=f17
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f17.dir
+InputName=f17
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f18.dir
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f18.dir
+InputName=f18
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f18.dir
+InputName=f18
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f19.dir
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f19.dir
+InputName=f19
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f19.dir
+InputName=f19
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f20.dir
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f20.dir
+InputName=f20
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f20.dir
+InputName=f20
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f21.dir
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f21.dir
+InputName=f21
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f21.dir
+InputName=f21
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f22.dir
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f22.dir
+InputName=f22
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f22.dir
+InputName=f22
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f23.dir
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f23.dir
+InputName=f23
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f23.dir
+InputName=f23
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f24.dir
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f24.dir
+InputName=f24
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f24.dir
+InputName=f24
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f25.dir
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f25.dir
+InputName=f25
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f25.dir
+InputName=f25
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f26.dir
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f26.dir
+InputName=f26
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f26.dir
+InputName=f26
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f27.dir
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f27.dir
+InputName=f27
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f27.dir
+InputName=f27
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f28.dir
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f28.dir
+InputName=f28
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f28.dir
+InputName=f28
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f29.dir
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f29.dir
+InputName=f29
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f29.dir
+InputName=f29
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\cg\f30.dir
+
+!IF  "$(CFG)" == "cg0 - Win32 Release"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\f30.dir
+InputName=f30
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg0 - Win32 Debug"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\f30.dir
+InputName=f30
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# End Group
 # Begin Source File
 
 SOURCE=.\Cg0.rc
diff --git a/projects/cg3.dsp b/projects/cg3.dsp
index 5d8e65908..7706589b6 100755
--- a/projects/cg3.dsp
+++ b/projects/cg3.dsp
@@ -43,7 +43,7 @@ RSC=rc.exe
 # PROP Ignore_Export_Lib 0
 # PROP Target_Dir ""
 # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c
-# ADD CPP /nologo /MT /W3 /O2 /I "..\include" /I "..\xvaga" /I "..\xi" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "XVT" /FD /c
+# ADD CPP /nologo /MT /W3 /O2 /I "..\include" /I "..\xvaga" /I "..\xi" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "XVT" /FR /FD /c
 # SUBTRACT CPP /YX
 # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /o "NUL" /win32
 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /o "NUL" /win32
diff --git a/projects/cg5.dsp b/projects/cg5.dsp
index 86b4f7ac8..109c5b08c 100755
--- a/projects/cg5.dsp
+++ b/projects/cg5.dsp
@@ -740,6 +740,33 @@ InputName=cg5800a
 # Begin Source File
 
 SOURCE=..\cg\cg5800ra.rep
+
+!IF  "$(CFG)" == "cg5 - Win32 Release"
+
+# Begin Custom Build - Copying rep $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\cg\cg5800ra.rep
+InputName=cg5800ra
+
+"$(TargetDir)\$(InputName).rep" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "cg5 - Win32 Debug"
+
+# Begin Custom Build - Copying rep $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\cg\cg5800ra.rep
+InputName=cg5800ra
+
+"$(TargetDir)\$(InputName).rep" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)
+
+# End Custom Build
+
+!ENDIF 
+
 # End Source File
 # End Group
 # Begin Source File
diff --git a/projects/li.dsw b/projects/li.dsw
new file mode 100755
index 000000000..95ebc5a8e
--- /dev/null
+++ b/projects/li.dsw
@@ -0,0 +1,44 @@
+Microsoft Developer Studio Workspace File, Format Version 6.00
+# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!
+
+###############################################################################
+
+Project: "AgaLib"=.\AgaLib.dsp - Package Owner=<4>
+
+Package=<5>
+{{{
+}}}
+
+Package=<4>
+{{{
+}}}
+
+###############################################################################
+
+Project: "li0"=.\li0.dsp - Package Owner=<4>
+
+Package=<5>
+{{{
+}}}
+
+Package=<4>
+{{{
+    Begin Project Dependency
+    Project_Dep_Name AgaLib
+    End Project Dependency
+}}}
+
+###############################################################################
+
+Global:
+
+Package=<5>
+{{{
+}}}
+
+Package=<3>
+{{{
+}}}
+
+###############################################################################
+
diff --git a/projects/li0.dsp b/projects/li0.dsp
new file mode 100755
index 000000000..062f4dd72
--- /dev/null
+++ b/projects/li0.dsp
@@ -0,0 +1,463 @@
+# Microsoft Developer Studio Project File - Name="li0" - Package Owner=<4>
+# Microsoft Developer Studio Generated Build File, Format Version 6.00
+# ** DO NOT EDIT **
+
+# TARGTYPE "Win32 (x86) Application" 0x0101
+
+CFG=li0 - Win32 Debug
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,
+!MESSAGE use the Export Makefile command and run
+!MESSAGE 
+!MESSAGE NMAKE /f "li0.mak".
+!MESSAGE 
+!MESSAGE You can specify a configuration when running NMAKE
+!MESSAGE by defining the macro CFG on the command line. For example:
+!MESSAGE 
+!MESSAGE NMAKE /f "li0.mak" CFG="li0 - Win32 Debug"
+!MESSAGE 
+!MESSAGE Possible choices for configuration are:
+!MESSAGE 
+!MESSAGE "li0 - Win32 Release" (based on "Win32 (x86) Application")
+!MESSAGE "li0 - Win32 Debug" (based on "Win32 (x86) Application")
+!MESSAGE 
+
+# Begin Project
+# PROP AllowPerConfigDependencies 0
+# PROP Scc_ProjName ""
+# PROP Scc_LocalPath ""
+CPP=cl.exe
+MTL=midl.exe
+RSC=rc.exe
+
+!IF  "$(CFG)" == "li0 - Win32 Release"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir "Release"
+# PROP BASE Intermediate_Dir "Release"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir "..\release"
+# PROP Intermediate_Dir "..\release"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c
+# ADD CPP /nologo /MT /W3 /O2 /I "..\include" /I "..\xvaga" /I "..\xi" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "XVT" /FR /FD /c
+# SUBTRACT CPP /YX
+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /o "NUL" /win32
+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /o "NUL" /win32
+# ADD BASE RSC /l 0x410 /d "NDEBUG"
+# ADD RSC /l 0x410 /i "..\..\wx240\include" /d "NDEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /machine:I386
+# ADD LINK32 version.lib wsock32.lib kernel32.lib gdi32.lib user32.lib advapi32.lib comdlg32.lib shell32.lib ole32.lib oleaut32.lib comctl32.lib rpcrt4.lib winspool.lib /nologo /subsystem:windows /machine:I386 /nodefaultlib:"libc.lib" /out:"D:\Release\Campo21/li0.exe"
+# SUBTRACT LINK32 /map /debug /nodefaultlib
+
+!ELSEIF  "$(CFG)" == "li0 - Win32 Debug"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 1
+# PROP BASE Output_Dir "Debug"
+# PROP BASE Intermediate_Dir "Debug"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 1
+# PROP Output_Dir "..\debug"
+# PROP Intermediate_Dir "..\debug"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /FD /c
+# ADD CPP /nologo /MTd /W3 /Gm /Zi /Od /I "..\include" /I "..\xvaga" /I "..\xi" /D "_DEBUG" /D "WIN32" /D "DBG" /D "_WINDOWS" /FR /FD /c
+# SUBTRACT CPP /YX
+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /o "NUL" /win32
+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /o "NUL" /win32
+# ADD BASE RSC /l 0x410 /d "_DEBUG"
+# ADD RSC /l 0x410 /i "..\..\wx240\include" /d "_DEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /debug /machine:I386 /pdbtype:sept
+# ADD LINK32 version.lib wsock32.lib kernel32.lib gdi32.lib user32.lib advapi32.lib comdlg32.lib shell32.lib ole32.lib oleaut32.lib comctl32.lib rpcrt4.lib winspool.lib /nologo /subsystem:windows /debug /machine:I386 /nodefaultlib:"libc.lib" /out:"..\exed\li0.exe" /pdbtype:sept
+# SUBTRACT LINK32 /nodefaultlib
+
+!ENDIF 
+
+# Begin Target
+
+# Name "li0 - Win32 Release"
+# Name "li0 - Win32 Debug"
+# Begin Group "Sources"
+
+# PROP Default_Filter "cpp"
+# Begin Source File
+
+SOURCE=..\li\li0.cpp
+# End Source File
+# Begin Source File
+
+SOURCE=..\li\li0400.cpp
+# End Source File
+# Begin Source File
+
+SOURCE=..\li\li0500.cpp
+# End Source File
+# Begin Source File
+
+SOURCE=..\li\li0600.cpp
+# End Source File
+# End Group
+# Begin Group "Masks"
+
+# PROP Default_Filter "uml"
+# Begin Source File
+
+SOURCE=..\li\li0400a.uml
+
+!IF  "$(CFG)" == "li0 - Win32 Release"
+
+# Begin Custom Build - Compiling mask $(InputPath)...
+TargetDir=D:\Release\Campo21
+InputPath=..\li\li0400a.uml
+InputName=li0400a
+
+"$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "li0 - Win32 Debug"
+
+# Begin Custom Build - Compiling mask $(InputPath)...
+TargetDir=\U\Luca\D_02_01\exed
+InputPath=..\li\li0400a.uml
+InputName=li0400a
+
+"$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\li\li0500a.uml
+
+!IF  "$(CFG)" == "li0 - Win32 Release"
+
+# Begin Custom Build - Compiling mask $(InputPath)...
+TargetDir=D:\Release\Campo21
+InputPath=..\li\li0500a.uml
+InputName=li0500a
+
+"$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "li0 - Win32 Debug"
+
+# Begin Custom Build - Compiling mask $(InputPath)...
+TargetDir=\U\Luca\D_02_01\exed
+InputPath=..\li\li0500a.uml
+InputName=li0500a
+
+"$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\li\li0500b.uml
+
+!IF  "$(CFG)" == "li0 - Win32 Release"
+
+# Begin Custom Build - Compiling mask $(InputPath)...
+TargetDir=D:\Release\Campo21
+InputPath=..\li\li0500b.uml
+InputName=li0500b
+
+"$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "li0 - Win32 Debug"
+
+# Begin Custom Build - Compiling mask $(InputPath)...
+TargetDir=\U\Luca\D_02_01\exed
+InputPath=..\li\li0500b.uml
+InputName=li0500b
+
+"$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\li\li0600a.uml
+
+!IF  "$(CFG)" == "li0 - Win32 Release"
+
+# Begin Custom Build - Compiling mask $(InputPath)...
+TargetDir=D:\Release\Campo21
+InputPath=..\li\li0600a.uml
+InputName=li0600a
+
+"$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "li0 - Win32 Debug"
+
+# Begin Custom Build - Compiling mask $(InputPath)...
+TargetDir=\U\Luca\D_02_01\exed
+InputPath=..\li\li0600a.uml
+InputName=li0600a
+
+"$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\li\li0600b.uml
+
+!IF  "$(CFG)" == "li0 - Win32 Release"
+
+# Begin Custom Build - Compiling mask $(InputPath)...
+TargetDir=D:\Release\Campo21
+InputPath=..\li\li0600b.uml
+InputName=li0600b
+
+"$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "li0 - Win32 Debug"
+
+# Begin Custom Build - Compiling mask $(InputPath)...
+TargetDir=\U\Luca\D_02_01\exed
+InputPath=..\li\li0600b.uml
+InputName=li0600b
+
+"$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# End Group
+# Begin Group "Headers"
+
+# PROP Default_Filter "h"
+# Begin Source File
+
+SOURCE=..\li\letint.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\li\li0.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\li\li0400a.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\li\li0500a.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\li\li0500b.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\li\li0600a.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\li\li0600b.h
+# End Source File
+# End Group
+# Begin Group "Trrs"
+
+# PROP Default_Filter "trr"
+# Begin Source File
+
+SOURCE=..\li\f154.trr
+
+!IF  "$(CFG)" == "li0 - Win32 Release"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=D:\Release\Campo21
+InputPath=..\li\f154.trr
+InputName=f154
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "li0 - Win32 Debug"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=\U\Luca\D_02_01\exed
+InputPath=..\li\f154.trr
+InputName=f154
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# End Group
+# Begin Group "Dirs"
+
+# PROP Default_Filter "dir"
+# Begin Source File
+
+SOURCE=..\li\f154.dir
+
+!IF  "$(CFG)" == "li0 - Win32 Release"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=D:\Release\Campo21
+InputPath=..\li\f154.dir
+InputName=f154
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "li0 - Win32 Debug"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=\U\Luca\D_02_01\exed
+InputPath=..\li\f154.dir
+InputName=f154
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# End Group
+# Begin Group "Reports"
+
+# PROP Default_Filter "rep"
+# Begin Source File
+
+SOURCE=..\li\li0500a.rep
+
+!IF  "$(CFG)" == "li0 - Win32 Release"
+
+# Begin Custom Build - Copying report $(InputPath)...
+TargetDir=D:\Release\Campo21
+InputPath=..\li\li0500a.rep
+InputName=li0500a
+
+"$(TargetDir)\$(InputName).rep" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\$(InputName).rep
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "li0 - Win32 Debug"
+
+# Begin Custom Build - Copying report $(InputPath)...
+TargetDir=\U\Luca\D_02_01\exed
+InputPath=..\li\li0500a.rep
+InputName=li0500a
+
+"$(TargetDir)\$(InputName).rep" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\$(InputName).rep
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# End Group
+# Begin Group "Ini"
+
+# PROP Default_Filter "ini"
+# Begin Source File
+
+SOURCE=..\li\li0600a.ini
+
+!IF  "$(CFG)" == "li0 - Win32 Release"
+
+# Begin Custom Build - Copying ini $(InputPath)...
+TargetDir=D:\Release\Campo21
+InputPath=..\li\li0600a.ini
+InputName=li0600a
+
+"$(TargetDir)\$(InputName).ini" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\$(InputName).ini
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "li0 - Win32 Debug"
+
+# Begin Custom Build - Copying ini $(InputPath)...
+TargetDir=\U\Luca\D_02_01\exed
+InputPath=..\li\li0600a.ini
+InputName=li0600a
+
+"$(TargetDir)\$(InputName).ini" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\$(InputName).ini
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# End Group
+# Begin Source File
+
+SOURCE=.\li0.rc
+
+!IF  "$(CFG)" == "li0 - Win32 Release"
+
+# ADD BASE RSC /l 0x410
+# ADD RSC /l 0x410
+
+!ELSEIF  "$(CFG)" == "li0 - Win32 Debug"
+
+# ADD BASE RSC /l 0x410
+# ADD RSC /l 0x410 /fo"..\Debug/li0.res"
+
+!ENDIF 
+
+# End Source File
+# End Target
+# End Project
diff --git a/projects/scp0.rc b/projects/li0.rc
similarity index 100%
rename from projects/scp0.rc
rename to projects/li0.rc
diff --git a/projects/mr0.dsp b/projects/mr0.dsp
index cc5093297..bb7d143ad 100755
--- a/projects/mr0.dsp
+++ b/projects/mr0.dsp
@@ -96,10 +96,22 @@ LINK32=link.exe
 # PROP Default_Filter "cpp"
 # Begin Source File
 
+SOURCE=..\cg\cg2103.cpp
+# End Source File
+# Begin Source File
+
 SOURCE=..\cg\cglib01.cpp
 # End Source File
 # Begin Source File
 
+SOURCE=..\cg\cgpagame.cpp
+# End Source File
+# Begin Source File
+
+SOURCE=..\ve\clifor.cpp
+# End Source File
+# Begin Source File
+
 SOURCE=..\db\dblib.cpp
 # End Source File
 # Begin Source File
@@ -134,6 +146,46 @@ SOURCE=..\mr\mr0500.cpp
 
 SOURCE=..\mr\mrplib.cpp
 # End Source File
+# Begin Source File
+
+SOURCE=..\pr\prlib01.cpp
+# End Source File
+# Begin Source File
+
+SOURCE=..\ve\sconti.cpp
+# End Source File
+# Begin Source File
+
+SOURCE=..\sv\svlib01.cpp
+# End Source File
+# Begin Source File
+
+SOURCE=..\sv\svlib09.cpp
+# End Source File
+# Begin Source File
+
+SOURCE=..\ve\velib01.cpp
+# End Source File
+# Begin Source File
+
+SOURCE=..\ve\velib02.cpp
+# End Source File
+# Begin Source File
+
+SOURCE=..\ve\velib03.cpp
+# End Source File
+# Begin Source File
+
+SOURCE=..\ve\velib03a.cpp
+# End Source File
+# Begin Source File
+
+SOURCE=..\ve\velib04.cpp
+# End Source File
+# Begin Source File
+
+SOURCE=..\ve\velib04e.cpp
+# End Source File
 # End Group
 # Begin Group "Masks"
 
@@ -202,6 +254,68 @@ InputName=mr0500a
 # End Source File
 # Begin Source File
 
+SOURCE=..\mr\mr0500b.uml
+
+!IF  "$(CFG)" == "mr0 - Win32 Release"
+
+# Begin Custom Build - Compiling mask $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\mr\mr0500b.uml
+InputName=mr0500b
+
+"$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "mr0 - Win32 Debug"
+
+# Begin Custom Build - Compiling mask $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\mr\mr0500b.uml
+InputName=mr0500b
+
+"$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\mr\mr0500c.uml
+
+!IF  "$(CFG)" == "mr0 - Win32 Release"
+
+# Begin Custom Build - Compiling mask $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\mr\mr0500c.uml
+InputName=mr0500c
+
+"$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "mr0 - Win32 Debug"
+
+# Begin Custom Build - Compiling mask $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\mr\mr0500c.uml
+InputName=mr0500c
+
+"$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
 SOURCE=..\mr\mrtbfia.uml
 
 !IF  "$(CFG)" == "mr0 - Win32 Release"
@@ -311,6 +425,14 @@ SOURCE=..\mr\mr0500a.h
 # End Source File
 # Begin Source File
 
+SOURCE=..\mr\mr0500b.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\mr\mr0500c.h
+# End Source File
+# Begin Source File
+
 SOURCE=..\mr\mrplib.h
 # End Source File
 # Begin Source File
@@ -324,6 +446,200 @@ SOURCE=..\mr\mrtbimp.h
 # Begin Source File
 
 SOURCE=..\mr\mrtblnp.h
+# End Source File
+# End Group
+# Begin Group "Trr"
+
+# PROP Default_Filter "trr"
+# Begin Source File
+
+SOURCE=..\mr\f132.trr
+
+!IF  "$(CFG)" == "mr0 - Win32 Release"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\mr\f132.trr
+InputName=f132
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "mr0 - Win32 Debug"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\mr\f132.trr
+InputName=f132
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\mr\f152.trr
+
+!IF  "$(CFG)" == "mr0 - Win32 Release"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\mr\f152.trr
+InputName=f152
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "mr0 - Win32 Debug"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\mr\f152.trr
+InputName=f152
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\mr\f153.trr
+
+!IF  "$(CFG)" == "mr0 - Win32 Release"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\mr\f153.trr
+InputName=f153
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "mr0 - Win32 Debug"
+
+# Begin Custom Build - Copying trr $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\mr\f153.trr
+InputName=f153
+
+"$(TargetDir)\recdesc\$(InputName).trr" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).trr
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# End Group
+# Begin Group "Dir"
+
+# PROP Default_Filter "dir"
+# Begin Source File
+
+SOURCE=..\mr\f132.dir
+
+!IF  "$(CFG)" == "mr0 - Win32 Release"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\mr\f132.dir
+InputName=f132
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "mr0 - Win32 Debug"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\mr\f132.dir
+InputName=f132
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\mr\f152.dir
+
+!IF  "$(CFG)" == "mr0 - Win32 Release"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\mr\f152.dir
+InputName=f152
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "mr0 - Win32 Debug"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\mr\f152.dir
+InputName=f152
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\mr\f153.dir
+
+!IF  "$(CFG)" == "mr0 - Win32 Release"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=D:\Release\Campo22
+InputPath=..\mr\f153.dir
+InputName=f153
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "mr0 - Win32 Debug"
+
+# Begin Custom Build - Copying dir $(InputPath)...
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\mr\f153.dir
+InputName=f153
+
+"$(TargetDir)\recdesc\$(InputName).dir" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\recdesc\$(InputName).dir
+
+# End Custom Build
+
+!ENDIF 
+
 # End Source File
 # End Group
 # Begin Source File
diff --git a/projects/mr1.dsp b/projects/mr1.dsp
index 466491db2..f98ab0877 100755
--- a/projects/mr1.dsp
+++ b/projects/mr1.dsp
@@ -71,7 +71,7 @@ LINK32=link.exe
 # PROP Ignore_Export_Lib 0
 # PROP Target_Dir ""
 # ADD BASE CPP /nologo /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /FD /c
-# ADD CPP /nologo /MTd /W3 /Gm /Zi /Od /I "..\include" /I "..\xvaga" /I "..\xi" /D "_DEBUG" /D "WIN32" /D "DBG" /D "_WINDOWS" /D "__LONGDOUBLE__" /FR /FD /c
+# ADD CPP /nologo /MTd /W3 /Gm /Zi /Od /I "..\include" /I "..\xvaga" /I "..\xi" /D "_DEBUG" /D "WIN32" /D "DBG" /D "_WINDOWS" /FR /FD /c
 # SUBTRACT CPP /YX
 # ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /o "NUL" /win32
 # ADD MTL /nologo /D "_DEBUG" /mktyplib203 /o "NUL" /win32
@@ -217,6 +217,14 @@ InputName=mr1100a
 # Begin Group "Headers"
 
 # PROP Default_Filter "h"
+# Begin Source File
+
+SOURCE=..\mr\mr1.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\mr\mr1100a.h
+# End Source File
 # End Group
 # Begin Group "Forms"
 
diff --git a/projects/Scp0.dsp b/projects/pd1890.dsp
similarity index 78%
rename from projects/Scp0.dsp
rename to projects/pd1890.dsp
index f4c884f1e..3c6bc70fe 100755
--- a/projects/Scp0.dsp
+++ b/projects/pd1890.dsp
@@ -1,24 +1,24 @@
-# Microsoft Developer Studio Project File - Name="scp0" - Package Owner=<4>
+# Microsoft Developer Studio Project File - Name="pd1890" - Package Owner=<4>
 # Microsoft Developer Studio Generated Build File, Format Version 6.00
 # ** DO NOT EDIT **
 
 # TARGTYPE "Win32 (x86) Application" 0x0101
 
-CFG=scp0 - Win32 Debug
+CFG=pd1890 - Win32 Debug
 !MESSAGE This is not a valid makefile. To build this project using NMAKE,
 !MESSAGE use the Export Makefile command and run
 !MESSAGE 
-!MESSAGE NMAKE /f "Scp0.mak".
+!MESSAGE NMAKE /f "pd1890.mak".
 !MESSAGE 
 !MESSAGE You can specify a configuration when running NMAKE
 !MESSAGE by defining the macro CFG on the command line. For example:
 !MESSAGE 
-!MESSAGE NMAKE /f "Scp0.mak" CFG="scp0 - Win32 Debug"
+!MESSAGE NMAKE /f "pd1890.mak" CFG="pd1890 - Win32 Debug"
 !MESSAGE 
 !MESSAGE Possible choices for configuration are:
 !MESSAGE 
-!MESSAGE "scp0 - Win32 Release" (based on "Win32 (x86) Application")
-!MESSAGE "scp0 - Win32 Debug" (based on "Win32 (x86) Application")
+!MESSAGE "pd1890 - Win32 Release" (based on "Win32 (x86) Application")
+!MESSAGE "pd1890 - Win32 Debug" (based on "Win32 (x86) Application")
 !MESSAGE 
 
 # Begin Project
@@ -29,7 +29,7 @@ CPP=cl.exe
 MTL=midl.exe
 RSC=rc.exe
 
-!IF  "$(CFG)" == "scp0 - Win32 Release"
+!IF  "$(CFG)" == "pd1890 - Win32 Release"
 
 # PROP BASE Use_MFC 0
 # PROP BASE Use_Debug_Libraries 0
@@ -54,10 +54,10 @@ BSC32=bscmake.exe
 # ADD BSC32 /nologo
 LINK32=link.exe
 # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /machine:I386
-# ADD LINK32 version.lib wsock32.lib kernel32.lib gdi32.lib user32.lib advapi32.lib comdlg32.lib shell32.lib ole32.lib oleaut32.lib comctl32.lib rpcrt4.lib winspool.lib /nologo /subsystem:windows /machine:I386 /nodefaultlib:"libc.lib" /out:"D:\Release\Campo22/scp0.exe"
+# ADD LINK32 version.lib wsock32.lib kernel32.lib gdi32.lib user32.lib advapi32.lib comdlg32.lib shell32.lib ole32.lib oleaut32.lib comctl32.lib rpcrt4.lib winspool.lib /nologo /subsystem:windows /machine:I386 /nodefaultlib:"libc.lib" /out:"D:\Release\Campo21/pd1890.exe"
 # SUBTRACT LINK32 /map /debug /nodefaultlib
 
-!ELSEIF  "$(CFG)" == "scp0 - Win32 Debug"
+!ELSEIF  "$(CFG)" == "pd1890 - Win32 Debug"
 
 # PROP BASE Use_MFC 0
 # PROP BASE Use_Debug_Libraries 1
@@ -82,15 +82,15 @@ BSC32=bscmake.exe
 # ADD BSC32 /nologo
 LINK32=link.exe
 # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /debug /machine:I386 /pdbtype:sept
-# ADD LINK32 version.lib wsock32.lib kernel32.lib gdi32.lib user32.lib advapi32.lib comdlg32.lib shell32.lib ole32.lib oleaut32.lib comctl32.lib rpcrt4.lib winspool.lib /nologo /subsystem:windows /debug /machine:I386 /nodefaultlib:"libc.lib" /out:"..\exed\scp0.exe" /pdbtype:sept
+# ADD LINK32 version.lib wsock32.lib kernel32.lib gdi32.lib user32.lib advapi32.lib comdlg32.lib shell32.lib ole32.lib oleaut32.lib comctl32.lib rpcrt4.lib winspool.lib /nologo /subsystem:windows /debug /machine:I386 /nodefaultlib:"libc.lib" /out:"..\exed\pd1890.exe" /pdbtype:sept
 # SUBTRACT LINK32 /nodefaultlib
 
 !ENDIF 
 
 # Begin Target
 
-# Name "scp0 - Win32 Release"
-# Name "scp0 - Win32 Debug"
+# Name "pd1890 - Win32 Release"
+# Name "pd1890 - Win32 Debug"
 # Begin Group "Sources"
 
 # PROP Default_Filter "cpp"
@@ -108,11 +108,11 @@ SOURCE=..\cg\cgsaldac.cpp
 # End Source File
 # Begin Source File
 
-SOURCE=..\sc\scp0.cpp
+SOURCE=..\ps\pd1890.cpp
 # End Source File
 # Begin Source File
 
-SOURCE=..\sc\scp0100.cpp
+SOURCE=..\ps\pd1890100.cpp
 # End Source File
 # End Group
 # Begin Group "Masks"
@@ -120,26 +120,26 @@ SOURCE=..\sc\scp0100.cpp
 # PROP Default_Filter "uml"
 # Begin Source File
 
-SOURCE=..\sc\scp0100a.uml
+SOURCE=..\ps\pd1890100a.uml
 
-!IF  "$(CFG)" == "scp0 - Win32 Release"
+!IF  "$(CFG)" == "pd1890 - Win32 Release"
 
 # Begin Custom Build - Compiling mask $(InputPath)...
-TargetDir=D:\Release\Campo22
-InputPath=..\sc\scp0100a.uml
-InputName=scp0100a
+TargetDir=D:\Release\Campo21
+InputPath=..\ps\pd1890100a.uml
+InputName=pd1890100a
 
 "$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
 	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
 
 # End Custom Build
 
-!ELSEIF  "$(CFG)" == "scp0 - Win32 Debug"
+!ELSEIF  "$(CFG)" == "pd1890 - Win32 Debug"
 
 # Begin Custom Build - Compiling mask $(InputPath)...
-TargetDir=\U\Luca\R_02_02\exed
-InputPath=..\sc\scp0100a.uml
-InputName=scp0100a
+TargetDir=\U\Luca\D_02_01\exed
+InputPath=..\ps\pd1890100a.uml
+InputName=pd1890100a
 
 "$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
 	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
@@ -153,10 +153,31 @@ InputName=scp0100a
 # Begin Group "Headers"
 
 # PROP Default_Filter "h"
+# Begin Source File
+
+SOURCE=..\ps\pd1890.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\ps\pd1890100.h
+# End Source File
 # End Group
 # Begin Source File
 
-SOURCE=.\scp0.rc
+SOURCE=.\pd1890.rc
+
+!IF  "$(CFG)" == "pd1890 - Win32 Release"
+
+# ADD BASE RSC /l 0x410
+# ADD RSC /l 0x410
+
+!ELSEIF  "$(CFG)" == "pd1890 - Win32 Debug"
+
+# ADD BASE RSC /l 0x410
+# ADD RSC /l 0x410 /fo"..\Debug/pd1890.res"
+
+!ENDIF 
+
 # End Source File
 # End Target
 # End Project
diff --git a/projects/pd1890.rc b/projects/pd1890.rc
new file mode 100755
index 000000000..898d4e0c0
--- /dev/null
+++ b/projects/pd1890.rc
@@ -0,0 +1,4 @@
+"9012"       ICON DISCARDABLE    "../exed/res/exe.ico"
+
+rcinclude ../../wx240/include/wx/msw/wx.rc
+
diff --git a/projects/pd6030.dsp b/projects/pd6030.dsp
new file mode 100755
index 000000000..eda7ef7fb
--- /dev/null
+++ b/projects/pd6030.dsp
@@ -0,0 +1,179 @@
+# Microsoft Developer Studio Project File - Name="pd6030" - Package Owner=<4>
+# Microsoft Developer Studio Generated Build File, Format Version 6.00
+# ** DO NOT EDIT **
+
+# TARGTYPE "Win32 (x86) Application" 0x0101
+
+CFG=pd6030 - Win32 Debug
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,
+!MESSAGE use the Export Makefile command and run
+!MESSAGE 
+!MESSAGE NMAKE /f "pd6030.mak".
+!MESSAGE 
+!MESSAGE You can specify a configuration when running NMAKE
+!MESSAGE by defining the macro CFG on the command line. For example:
+!MESSAGE 
+!MESSAGE NMAKE /f "pd6030.mak" CFG="pd6030 - Win32 Debug"
+!MESSAGE 
+!MESSAGE Possible choices for configuration are:
+!MESSAGE 
+!MESSAGE "pd6030 - Win32 Release" (based on "Win32 (x86) Application")
+!MESSAGE "pd6030 - Win32 Debug" (based on "Win32 (x86) Application")
+!MESSAGE 
+
+# Begin Project
+# PROP AllowPerConfigDependencies 0
+# PROP Scc_ProjName ""
+# PROP Scc_LocalPath ""
+CPP=cl.exe
+MTL=midl.exe
+RSC=rc.exe
+
+!IF  "$(CFG)" == "pd6030 - Win32 Release"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir "Release"
+# PROP BASE Intermediate_Dir "Release"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir "..\release"
+# PROP Intermediate_Dir "..\release"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c
+# ADD CPP /nologo /MT /W3 /O2 /I "..\include" /I "..\xvaga" /I "..\xi" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "XVT" /FD /c
+# SUBTRACT CPP /YX
+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /o "NUL" /win32
+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /o "NUL" /win32
+# ADD BASE RSC /l 0x410 /d "NDEBUG"
+# ADD RSC /l 0x410 /i "..\..\wx240\include" /d "NDEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /machine:I386
+# ADD LINK32 version.lib wsock32.lib kernel32.lib gdi32.lib user32.lib advapi32.lib comdlg32.lib shell32.lib ole32.lib oleaut32.lib comctl32.lib rpcrt4.lib winspool.lib /nologo /subsystem:windows /machine:I386 /nodefaultlib:"libc.lib" /out:"D:\Release\Campo21/pd6030.exe"
+# SUBTRACT LINK32 /map /debug /nodefaultlib
+
+!ELSEIF  "$(CFG)" == "pd6030 - Win32 Debug"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 1
+# PROP BASE Output_Dir "Debug"
+# PROP BASE Intermediate_Dir "Debug"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 1
+# PROP Output_Dir "..\debug"
+# PROP Intermediate_Dir "..\debug"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /FD /c
+# ADD CPP /nologo /MTd /W3 /Gm /Zi /Od /I "..\include" /I "..\xvaga" /I "..\xi" /D "_DEBUG" /D "WIN32" /D "DBG" /D "_WINDOWS" /FR /FD /c
+# SUBTRACT CPP /YX
+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /o "NUL" /win32
+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /o "NUL" /win32
+# ADD BASE RSC /l 0x410 /d "_DEBUG"
+# ADD RSC /l 0x410 /i "..\..\wx240\include" /d "_DEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /debug /machine:I386 /pdbtype:sept
+# ADD LINK32 version.lib wsock32.lib kernel32.lib gdi32.lib user32.lib advapi32.lib comdlg32.lib shell32.lib ole32.lib oleaut32.lib comctl32.lib rpcrt4.lib winspool.lib /nologo /subsystem:windows /debug /machine:I386 /nodefaultlib:"libc.lib" /out:"..\exed\pd6030.exe" /pdbtype:sept
+# SUBTRACT LINK32 /nodefaultlib
+
+!ENDIF 
+
+# Begin Target
+
+# Name "pd6030 - Win32 Release"
+# Name "pd6030 - Win32 Debug"
+# Begin Group "Sources"
+
+# PROP Default_Filter "cpp"
+# Begin Source File
+
+SOURCE=..\ps\pd6030.cpp
+# End Source File
+# Begin Source File
+
+SOURCE=..\ps\pd6030100.cpp
+# End Source File
+# End Group
+# Begin Group "Masks"
+
+# PROP Default_Filter "uml"
+# Begin Source File
+
+SOURCE=..\ps\pd6030100.uml
+
+!IF  "$(CFG)" == "pd6030 - Win32 Release"
+
+# Begin Custom Build - Compiling mask $(InputPath)...
+TargetDir=D:\Release\Campo21
+InputPath=..\ps\pd6030100.uml
+InputName=pd6030100
+
+"$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "pd6030 - Win32 Debug"
+
+# Begin Custom Build - Compiling mask $(InputPath)...
+TargetDir=\U\Luca\D_02_01\exed
+InputPath=..\ps\pd6030100.uml
+InputName=pd6030100
+
+"$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# End Group
+# Begin Group "Headers"
+
+# PROP Default_Filter "h"
+# Begin Source File
+
+SOURCE=..\ps\pd6030.h
+# End Source File
+# Begin Source File
+
+SOURCE=..\ps\pd6030100.h
+# End Source File
+# End Group
+# Begin Group "Reports"
+
+# PROP Default_Filter "rep"
+# Begin Source File
+
+SOURCE=..\ps\pd6030100a.rep
+# End Source File
+# End Group
+# Begin Source File
+
+SOURCE=.\pd6030.rc
+
+!IF  "$(CFG)" == "pd6030 - Win32 Release"
+
+# ADD BASE RSC /l 0x410
+# ADD RSC /l 0x410
+
+!ELSEIF  "$(CFG)" == "pd6030 - Win32 Debug"
+
+# ADD BASE RSC /l 0x410
+# ADD RSC /l 0x410 /fo"..\Debug/pd6030.res"
+
+!ENDIF 
+
+# End Source File
+# End Target
+# End Project
diff --git a/projects/pd6030.rc b/projects/pd6030.rc
new file mode 100755
index 000000000..898d4e0c0
--- /dev/null
+++ b/projects/pd6030.rc
@@ -0,0 +1,4 @@
+"9012"       ICON DISCARDABLE    "../exed/res/exe.ico"
+
+rcinclude ../../wx240/include/wx/msw/wx.rc
+
diff --git a/projects/ps.dsw b/projects/ps.dsw
index d4f7b40d7..f25846cbc 100755
--- a/projects/ps.dsw
+++ b/projects/ps.dsw
@@ -30,6 +30,36 @@ Package=<4>
 
 ###############################################################################
 
+Project: "pd1890"=.\pd1890.dsp - Package Owner=<4>
+
+Package=<5>
+{{{
+}}}
+
+Package=<4>
+{{{
+    Begin Project Dependency
+    Project_Dep_Name AgaLib
+    End Project Dependency
+}}}
+
+###############################################################################
+
+Project: "pd6030"=.\pd6030.dsp - Package Owner=<4>
+
+Package=<5>
+{{{
+}}}
+
+Package=<4>
+{{{
+    Begin Project Dependency
+    Project_Dep_Name AgaLib
+    End Project Dependency
+}}}
+
+###############################################################################
+
 Project: "ps"=.\ps.dsp - Package Owner=<4>
 
 Package=<5>
diff --git a/projects/ve7.dsp b/projects/ve7.dsp
index ab44fd73d..2684a80d7 100755
--- a/projects/ve7.dsp
+++ b/projects/ve7.dsp
@@ -533,6 +533,103 @@ InputName=ve7300a
 
 !ENDIF 
 
+# End Source File
+# End Group
+# Begin Group "Ini"
+
+# PROP Default_Filter ""
+# Begin Source File
+
+SOURCE=..\ve\mainardi.ini
+
+!IF  "$(CFG)" == "ve7 - Win32 Release"
+
+# Begin Custom Build - Copying ini $(InputPath)...
+TargetDir=D:\Release\Campo21
+InputPath=..\ve\mainardi.ini
+InputName=mainardi
+
+"$(TargetDir)\$(InputName).ini" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\$(InputName).ini
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "ve7 - Win32 Debug"
+
+# Begin Custom Build - Copying ini $(InputPath)...
+TargetDir=\U\Luca\D_02_01\exed
+InputPath=..\ve\mainardi.ini
+InputName=mainardi
+
+"$(TargetDir)\$(InputName).ini" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\$(InputName).ini
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\ve\ve7500m.ini
+
+!IF  "$(CFG)" == "ve7 - Win32 Release"
+
+# Begin Custom Build - Copying ini $(InputPath)...
+TargetDir=D:\Release\Campo21
+InputPath=..\ve\ve7500m.ini
+InputName=ve7500m
+
+"$(TargetDir)\$(InputName).ini" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\$(InputName).ini
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "ve7 - Win32 Debug"
+
+# Begin Custom Build - Copying ini $(InputPath)...
+TargetDir=\U\Luca\D_02_01\exed
+InputPath=..\ve\ve7500m.ini
+InputName=ve7500m
+
+"$(TargetDir)\$(InputName).ini" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\$(InputName).ini
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
+SOURCE=..\ve\ve7500p.ini
+
+!IF  "$(CFG)" == "ve7 - Win32 Release"
+
+# Begin Custom Build - Copying ini $(InputPath)...
+TargetDir=D:\Release\Campo21
+InputPath=..\ve\ve7500p.ini
+InputName=ve7500p
+
+"$(TargetDir)\$(InputName).ini" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\$(InputName).ini
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "ve7 - Win32 Debug"
+
+# Begin Custom Build - Copying ini $(InputPath)...
+TargetDir=\U\Luca\D_02_01\exed
+InputPath=..\ve\ve7500p.ini
+InputName=ve7500p
+
+"$(TargetDir)\$(InputName).ini" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	copy $(InputPath) $(TargetDir)\$(InputName).ini
+
+# End Custom Build
+
+!ENDIF 
+
 # End Source File
 # End Group
 # Begin Source File
diff --git a/projects/ve_masktab.dsp b/projects/ve_masktab.dsp
index 3a47d8a1d..001d575df 100755
--- a/projects/ve_masktab.dsp
+++ b/projects/ve_masktab.dsp
@@ -1148,6 +1148,37 @@ InputName=batbpro
 # End Source File
 # Begin Source File
 
+SOURCE=..\ve\batbprs.uml
+
+!IF  "$(CFG)" == "ve_masktab - Win32 Release"
+
+# Begin Custom Build - Compiling mask $(InputPath)
+TargetDir=D:\Release\Campo22
+InputPath=..\ve\batbprs.uml
+InputName=batbprs
+
+"$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "ve_masktab - Win32 Debug"
+
+# Begin Custom Build - Compiling mask $(InputPath)
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\ve\batbprs.uml
+InputName=batbprs
+
+"$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
 SOURCE=..\ve\batbprv.uml
 
 !IF  "$(CFG)" == "ve_masktab - Win32 Release"
@@ -1210,6 +1241,37 @@ InputName=batbrfa
 # End Source File
 # Begin Source File
 
+SOURCE=..\ve\batbspp.uml
+
+!IF  "$(CFG)" == "ve_masktab - Win32 Release"
+
+# Begin Custom Build - Compiling mask $(InputPath)
+TargetDir=D:\Release\Campo22
+InputPath=..\ve\batbspp.uml
+InputName=batbspp
+
+"$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
+
+# End Custom Build
+
+!ELSEIF  "$(CFG)" == "ve_masktab - Win32 Debug"
+
+# Begin Custom Build - Compiling mask $(InputPath)
+TargetDir=\U\Luca\R_02_02\exed
+InputPath=..\ve\batbspp.uml
+InputName=batbspp
+
+"$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
+	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
+
+# End Custom Build
+
+!ENDIF 
+
+# End Source File
+# Begin Source File
+
 SOURCE=..\ve\batbspt.uml
 
 !IF  "$(CFG)" == "ve_masktab - Win32 Release"
@@ -1396,14 +1458,14 @@ InputName=batbums
 # End Source File
 # Begin Source File
 
-SOURCE=..\ve\vetbatr.uml
+SOURCE=..\ve\vetbdip.uml
 
 !IF  "$(CFG)" == "ve_masktab - Win32 Release"
 
 # Begin Custom Build - Compiling mask $(InputPath)...
 TargetDir=D:\Release\Campo22
-InputPath=..\ve\vetbatr.uml
-InputName=vetbatr
+InputPath=..\ve\vetbdip.uml
+InputName=vetbdip
 
 "$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
 	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
@@ -1414,39 +1476,8 @@ InputName=vetbatr
 
 # Begin Custom Build - Compiling mask $(InputPath)...
 TargetDir=\U\Luca\R_02_02\exed
-InputPath=..\ve\vetbatr.uml
-InputName=vetbatr
-
-"$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
-	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
-
-# End Custom Build
-
-!ENDIF 
-
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\vetbnum.uml
-
-!IF  "$(CFG)" == "ve_masktab - Win32 Release"
-
-# Begin Custom Build - Compiling mask $(InputPath)...
-TargetDir=D:\Release\Campo22
-InputPath=..\ve\vetbnum.uml
-InputName=vetbnum
-
-"$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
-	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
-
-# End Custom Build
-
-!ELSEIF  "$(CFG)" == "ve_masktab - Win32 Debug"
-
-# Begin Custom Build - Compiling mask $(InputPath)...
-TargetDir=\U\Luca\R_02_02\exed
-InputPath=..\ve\vetbnum.uml
-InputName=vetbnum
+InputPath=..\ve\vetbdip.uml
+InputName=vetbdip
 
 "$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
 	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
@@ -1486,219 +1517,6 @@ InputName=vetbpci
 
 !ENDIF 
 
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\vetbprs.uml
-
-!IF  "$(CFG)" == "ve_masktab - Win32 Release"
-
-# Begin Custom Build - Compiling mask $(InputPath)...
-TargetDir=D:\Release\Campo22
-InputPath=..\ve\vetbprs.uml
-InputName=vetbprs
-
-"$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
-	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
-
-# End Custom Build
-
-!ELSEIF  "$(CFG)" == "ve_masktab - Win32 Debug"
-
-# Begin Custom Build - Compiling mask $(InputPath)...
-TargetDir=\U\Luca\R_02_02\exed
-InputPath=..\ve\vetbprs.uml
-InputName=vetbprs
-
-"$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
-	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
-
-# End Custom Build
-
-!ENDIF 
-
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\vetbrss.uml
-
-!IF  "$(CFG)" == "ve_masktab - Win32 Release"
-
-# Begin Custom Build - Compiling mask $(InputPath)...
-TargetDir=D:\Release\Campo22
-InputPath=..\ve\vetbrss.uml
-InputName=vetbrss
-
-"$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
-	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
-
-# End Custom Build
-
-!ELSEIF  "$(CFG)" == "ve_masktab - Win32 Debug"
-
-# Begin Custom Build - Compiling mask $(InputPath)...
-TargetDir=\U\Luca\R_02_02\exed
-InputPath=..\ve\vetbrss.uml
-InputName=vetbrss
-
-"$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
-	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
-
-# End Custom Build
-
-!ENDIF 
-
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\vetbspp.uml
-
-!IF  "$(CFG)" == "ve_masktab - Win32 Release"
-
-# Begin Custom Build - Compiling mask $(InputPath)...
-TargetDir=D:\Release\Campo22
-InputPath=..\ve\vetbspp.uml
-InputName=vetbspp
-
-"$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
-	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
-
-# End Custom Build
-
-!ELSEIF  "$(CFG)" == "ve_masktab - Win32 Debug"
-
-# Begin Custom Build - Compiling mask $(InputPath)...
-TargetDir=\U\Luca\R_02_02\exed
-InputPath=..\ve\vetbspp.uml
-InputName=vetbspp
-
-"$(TargetDir)\$(InputName).msk" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
-	msk32 $(InputPath) $(TargetDir)\$(InputName).msk
-
-# End Custom Build
-
-!ENDIF 
-
-# End Source File
-# End Group
-# Begin Group "Headers"
-
-# PROP Default_Filter "h"
-# Begin Source File
-
-SOURCE=..\ve\batbabe.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\batbacr.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\batbcaa.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\batbcld.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\batbcra.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\batbeld.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\batbfid.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\batbfrd.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\batbfrm.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\batbgmc.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\batbimb.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\batbmag.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\batbmre.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\batbnum.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\batbpro.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\batbrfa.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\batbspt.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\batbstd.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\batbtag.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\batbtip.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\batbtri.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\batbums.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\vetbatr.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\vetbdip.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\vetbnum.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\vetbpci.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\vetbprs.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\vetbrss.h
-# End Source File
-# Begin Source File
-
-SOURCE=..\ve\vetbspp.h
 # End Source File
 # End Group
 # End Target
diff --git a/sc/sc2600.cpp b/sc/sc2600.cpp
index f62925b9c..8debb4485 100755
--- a/sc/sc2600.cpp
+++ b/sc/sc2600.cpp
@@ -333,13 +333,13 @@ void TProspettoScadenze::compute_all(TPartita& p, TBill& bill)
       }
       if (d <= _limscad && d >= (TDate&)_s_date[0])
         s1 += res;
-      if (d < (TDate&)_s_date[0] && d >= (TDate&)_s_date[1])
+      if (d < (TDate&)_s_date[0] && d >= (TDate&)_s_date[1]) 
         s2 += res;
       if (d < (TDate&)_s_date[1] && d >= (TDate&)_s_date[2])
         s3 += res;
       if (d < (TDate&)_s_date[2] && d >= (TDate&)_s_date[3])
         s4 += res;
-      if (d < (TDate&)_s_date[3] && d >= (TDate&)_s_date[4])
+      if (d < (TDate&)_s_date[3] && d >= (TDate&)_s_date[4]) 
         s5 += res;
       if (d < (TDate&)_s_date[4])
         s6 += res;
@@ -686,28 +686,20 @@ void TProspettoScadenze::print_totali_rows(int& nriga, bool what)
       
 		if (_sinfasce)
 		{               
-	    if (v._s1 != ZERO)              
+	    if (v._s6 != ZERO)              
 	    {
-		    print_real(value, v._s1);
+		    print_real(value, v._s6);
 	      rw << format("@%dg%15s", pos, (const char*) value);
 	    }  
-	    if (_sfasce >= 1)
+	    if (_sfasce >= 5)
 	    	pos = pos + 16;
 	
-	    if (v._s2 != ZERO)
+	    if (v._s5 != ZERO)
 	    {
-		    print_real(value, v._s2);
+		    print_real(value, v._s5);
 	      rw << format("@%dg%15s", pos, (const char*) value);
 	    }  
-	    if (_sfasce >= 2)
-	    	pos = pos + 16;
-	
-	    if (v._s3 != ZERO)
-	    {
-		    print_real(value, v._s3);
-	      rw << format("@%dg%15s", pos, (const char*) value);
-	    }  
-	    if (_sfasce >= 3)
+	    if (_sfasce >= 4)
 	    	pos = pos + 16;
 	
 	    if (v._s4 != ZERO)
@@ -715,20 +707,28 @@ void TProspettoScadenze::print_totali_rows(int& nriga, bool what)
 		    print_real(value, v._s4);
 	      rw << format("@%dg%15s", pos, (const char*) value);
 	    }  
-	    if (_sfasce >= 4)
+	    if (_sfasce >= 3)
 	    	pos = pos + 16;
 	
-	    if (v._s5 != ZERO)       
+	    if (v._s3 != ZERO)
 	    {
-	    	print_real(value, v._s5);
+		    print_real(value, v._s3);
 	      rw << format("@%dg%15s", pos, (const char*) value);
 	    }  
-	    if (_sfasce >= 5)
+	    if (_sfasce >= 2)
+	    	pos = pos + 16;
+	
+	    if (v._s2 != ZERO)       
+	    {
+	    	print_real(value, v._s2);
+	      rw << format("@%dg%15s", pos, (const char*) value);
+	    }  
+	    if (_sfasce >= 1)
 	    	pos = pos + 16;
     }
-    if (v._s6 != ZERO)
+    if (v._s1 != ZERO)
     {
-	    print_real(value, v._s6);
+	    print_real(value, v._s1);
       rw << format("@%dg%15s", pos, (const char*) value);
     }  
    	pos = pos + 16;
@@ -880,31 +880,30 @@ void TProspettoScadenze::print_header()
    	rw = "";
     if (_sinfasce)
     {
-    	rw << format("@%dg%15s", pos, "0 gg");
-    	for (int i = 0; i < _sfasce; i++)
+			for (int i = _sfasce-1; i >= 0; i--)
     	{
-    		pos = pos + 16;
     		rw << format("@%dg%12d gg", pos, limiti[row][i]);
+    		pos = pos + 16;
     	}                
-    	set_header(soh, format("@%dg%15s", 60+((pos-60)/2)-4, "SCADUTO"));
+	   	rw << format("@%dg%15s", pos, "0 gg");
+    	set_header(soh, format("@%dg%15s", 60+((pos-60)/2), "SCADUTO"));
     }
     else
     	set_header(soh, format("@%dg%15s", pos, "SCADUTO"));
-    pos = pos + 16;	
+		pos = pos + 16;
     const int pos_ascad = pos;
     if (_nsinfasce)	
     {
-    	rw << format("@%dg%15s", pos, "0 gg");
     	for (int i = 0; i < _nsfasce; i++)
     	{
-    		pos = pos + 16;
     		rw << format("@%dg%12d gg", pos, limiti[row][i]);
+    		pos = pos + 16;
     	}
     	set_header(soh, format("@%dg%15s", pos_ascad+((pos-pos_ascad)/2)-5, "A SCADERE"));
     }
     else
     	set_header(soh, format("@%dg%15s", pos, "A SCADERE"));
-    pos = pos + 16;
+		pos = pos + 16;
    	set_header(soh, format("@%dg%15s", pos, "TOTALE"));
    	pos = pos + 16;
    	set_header(soh, format("@%dg%15s", pos, "ESPOSTO"));
diff --git a/server/authoriz.cpp b/server/authoriz.cpp
index 169d04c19..e88c2d5e1 100755
--- a/server/authoriz.cpp
+++ b/server/authoriz.cpp
@@ -38,6 +38,7 @@ public:
 	TUserInfo* Find(wxSocketBase& sock, const wxChar* user, int session);
 	void RemoveConnection(wxSocketBase& sock, const wxChar* user, int session);
 	void Kill(const wxChar* user);
+  void KillSession(wxSocketBase& sock, int session);
 
 	size_t GetCount() const { return m_Hash.GetCount(); } 
 	size_t GetLicenses(); 
@@ -120,6 +121,18 @@ void TUserTable::Kill(const wxChar* strUser)
 	}
 }
 
+void TUserTable::KillSession(wxSocketBase& sock, int session)
+{
+  while (true)
+  {
+	  TUserInfo* ui = Find(sock, NULL, session);
+		if (ui != NULL)
+		  m_Hash.Delete(wxString::Format("%s@%s", ui->m_strName.c_str(), ui->m_strHost.c_str()));
+    else
+			break;
+	}
+}
+
 TUserTable::TUserTable(size_t size) : m_Hash(wxKEY_STRING, size) 
 { 
 	m_Hash.DeleteContents(true); 
@@ -817,15 +830,18 @@ void TAuthorizationServer::ProcessUserLogin(wxString cmd, wxSocketBase& sock)
 bool TAuthorizationServer::ProcessUserLogout(wxString cmd, wxSocketBase& sock)
 {
 	wxChar strUser[16];
+  wxChar strProgram[16];
 	int session;
 	
 	cmd.Replace(",", " "); 	cmd.Replace(")", " ");
-	const int nStr = sscanf(cmd, "UserLogout(%s %d)", strUser, &session);
+	const int nStr = sscanf(cmd, "UserLogout(%s %d %s)", strUser, &session, strProgram);
 
 	if (nStr < 2)
 		session = 0;
 
   m_Users.RemoveConnection(sock, strUser, session);
+  if (strcmp(strProgram, "ba0100") == 0)
+    m_Users.KillSession(sock, session);
 
 	return true;
 }
diff --git a/ve/batbeld.h b/ve/batbeld.h
index 9fdd6b7e4..5c82f48c0 100755
--- a/ve/batbeld.h
+++ b/ve/batbeld.h
@@ -50,6 +50,7 @@
 #define F_ORDINA                168
 #define F_PROTOCOLLO            169
 #define F_USA_DCONS             170
+#define F_KILLDESC							171
 
 #define H_DOC1                  180
 #define H_DOC2                  181
diff --git a/ve/batbeld.uml b/ve/batbeld.uml
index 00dfe8adf..385eeabe5 100755
--- a/ve/batbeld.uml
+++ b/ve/batbeld.uml
@@ -46,19 +46,19 @@ LIST F_TIPO 50
 BEGIN
   PROMPT 2 3 "Tipo        "
   ITEM " |Esterna"
-    MESSAGE HIDE,1@|HIDE,2@|HIDE,3@|HIDE,4@|HIDE,5@|SHOW,9@
+    MESSAGE HIDE,1@|HIDE,2@|HIDE,3@|HIDE,4@|HIDE,5@|SHOW,9@|SHOW,F_KILLDESC
   ITEM "1|Consegna Ordini"
-    MESSAGE SHOW,1@|HIDE,2@|HIDE,3@|HIDE,4@|HIDE,5@|HIDE,9@
+    MESSAGE SHOW,1@|HIDE,2@|HIDE,3@|HIDE,4@|HIDE,5@|HIDE,9@|SHOW,F_KILLDESC
   ITEM "2|Fatturazione bolle"
-    MESSAGE HIDE,1@|SHOW,2@|HIDE,3@|HIDE,4@|HIDE,5@|HIDE,9@
+    MESSAGE HIDE,1@|SHOW,2@|HIDE,3@|HIDE,4@|HIDE,5@|HIDE,9@|SHOW,F_KILLDESC
   ITEM "3|Trasferimento a contabilita'"
-    MESSAGE HIDE,1@|HIDE,2@|SHOW,3@|HIDE,4@|HIDE,5@|SHOW,9@
+    MESSAGE HIDE,1@|HIDE,2@|SHOW,3@|HIDE,4@|HIDE,5@|SHOW,9@|HIDE,F_KILLDESC
   ITEM "4|Copia documento"
-    MESSAGE HIDE,1@|HIDE,2@|HIDE,3@|SHOW,4@|HIDE,5@|HIDE,9@
+    MESSAGE HIDE,1@|HIDE,2@|HIDE,3@|SHOW,4@|HIDE,5@|HIDE,9@|HIDE,F_KILLDESC
   ITEM "5|Generazione effetti"
-    MESSAGE HIDE,1@|HIDE,2@|HIDE,3@|HIDE,4@|SHOW,5@|HIDE,9@
+    MESSAGE HIDE,1@|HIDE,2@|HIDE,3@|HIDE,4@|SHOW,5@|HIDE,9@|HIDE,F_KILLDESC
   ITEM "6|Consuntivazione produzione"
-    MESSAGE SHOW,1@|HIDE,2@|HIDE,3@|HIDE,4@|HIDE,5@|HIDE,9@
+    MESSAGE SHOW,1@|HIDE,2@|HIDE,3@|HIDE,4@|HIDE,5@|HIDE,9@|SHOW,F_KILLDESC
   FIELD I0
 END
 
@@ -517,7 +517,12 @@ BEGIN
    ITEM "X|Da registro IVA"
    FIELD B4
    GROUP 3
+END
 
+BOOLEAN F_KILLDESC
+BEGIN
+	PROMPT 45 15 "Non riportare descrizione estesa"
+	FIELD B10
 END
 
 BOOLEAN F_AGGIORNA_TESTATA
diff --git a/ve/mainardi.ini b/ve/mainardi.ini
new file mode 100755
index 000000000..c829a6076
--- /dev/null
+++ b/ve/mainardi.ini
@@ -0,0 +1,286 @@
+[MAIN]
+DECSEP = ,
+FIELDSEP =
+RECORDSEP =
+RECORDSIZE = 128
+SKIPLINES = 0
+TYPEFIELD = -1
+TYPELEN = -1
+TYPEPOS = -1
+
+[TYPE FISSO]
+ALIGN =
+DATA =
+DECIMAL = 0
+FILLER = ' '
+LENGTH = 0
+PICTURE =
+
+[TYPE DATA]
+ALIGN =
+DATA = D
+DECIMAL = 0
+FILLER =
+LENGTH = 6
+PICTURE =
+
+[TYPE NUMERO]
+ALIGN = R
+DATA = N
+DECIMAL = 0
+FILLER = '0'
+LENGTH = 0
+PICTURE =
+
+[TYPE STRINGA]
+ALIGN = L
+DATA = S
+DECIMAL = 0
+FILLER = ' '
+LENGTH = 0
+PICTURE =
+
+[TYPE IMPORTO]
+ALIGN = R
+DATA = S
+DECIMAL = 0
+FILLER = '0'
+LENGTH = 0
+PICTURE =
+
+[HEADER 01]
+NAME(0)=TIPO RECORD
+TYPE(0)=FISSO
+LENGTH(0)=2
+POSITION(0)=0
+MESSAGE(0)=_FISSO,!01
+FIELD(0)=
+
+NAME(1) = NUMERO PROGRESSIVO
+TYPE(1) = NUMERO
+LENGTH(1) = 5
+POSITION(1) = 2
+MESSAGE(1) = _PROGRESSIVO
+
+NAME(2) = NUMERO FATTURA
+TYPE(2) = NUMERO
+LENGTH(2) = 6
+POSITION(2) = 7
+
+NAME(3) =  DATA FATTURA
+TYPE(3) =
+LENGTH(3) = 6
+POSITION(3) = 13
+
+NAME(4) = NUMERO BOLLA
+TYPE(4) = NUMERO
+LENGTH(4) = 6
+POSITION(4) = 19
+MESSAGE(4) = _BOLLA,NUMERO
+FIELD(4) = 33->NDOC
+
+NAME(5) = DATA BOLLA
+TYPE(5) =
+LENGTH(5) = 6
+POSITION(5) = 25
+MESSAGE(5) = _BOLLA,DATA
+
+NAME(6) = CODICE FORNITORE
+ALIGN(6) = R
+DATA(6) = S
+LENGTH(6) = 15
+POSITION(6) = 31
+MESSAGE(6) = _FORNITORE
+
+NAME(7) = TIPO FORNITORE
+TYPE(7) =
+LENGTH(7) = 1
+POSITION(7) = 46
+
+NAME(8) = CODICE CLIENTE
+TYPE(8) =
+LENGTH(8) = 15
+POSITION(8) = 47
+FIELD(8) = 33->CODCF
+
+NAME(9) = CODICE COOPERATIVA
+TYPE(9) =
+LENGTH(9) = 15
+POSITION(9) = 62
+
+NAME(10) = CODICE SOCIO
+ALIGN(10) = R
+DATA(10) = S
+LENGTH(10) = 15
+POSITION(10) = 77
+FIELD(10) = 17->CODPRCF
+
+NAME(11) = TIPO SOCIO
+TYPE(11) =
+LENGTH(11) = 1
+POSITION(11) = 92
+
+NAME(12) = TIPO DOCUMENTO
+TYPE(12) = STRINGA
+LENGTH(12) = 1
+POSITION(12) = 93
+MESSAGE(12) = _FISSO,!F
+
+NAME(13) = CODICE DIVISA
+TYPE(13) =
+LENGTH(13) = 3
+POSITION(13) = 94
+MESSAGE(13) = _FISSO,!EUR
+
+NAME(14) = FILLER
+TYPE(14) =
+LENGTH(14) = 25
+POSITION(14) = 97
+
+NAME(15) = RISERVATO
+TYPE(15) =
+LENGTH(15) = 6
+POSITION(15) = 122
+
+[RECORD 02]
+
+NAME(0) = TIPO RECORD
+TYPE(0) =
+LENGTH(0) = 2
+POSITION(0) = 0
+MESSAGE(0) = _FISSO,!02
+
+NAME(1) = NUMERO PROGRESSIVO
+TYPE(1) =
+LENGTH(1) = 5
+POSITION(1) = 2
+MESSAGE(1) = _PROGRESSIVO
+FILLER(1) = '0'
+
+NAME(2) = CODICE ARTICOLO
+TYPE(2) =
+LENGTH(2) = 15
+POSITION(2) = 7
+FIELD(2) = 34->CODART
+
+NAME(3) = DESCRIZIONE ARTICOLO
+TYPE(3) =
+LENGTH(3) = 30
+POSITION(3) = 22
+FIELD(3) = 34->DESCR
+
+NAME(4) = UNITA DI MISURA
+TYPE(4) =
+LENGTH(4) = 2
+POSITION(4) = 52
+FIELD(4) = 34->UMQTA
+
+NAME(5) = QUANTITA FATTURATA
+LENGTH(5) = 7
+TYPE(5) = IMPORTO
+POSITION(5) = 54
+MESSAGE(5) = _RIGABOLLA,QUANTITA
+
+NAME(6) = PREZZO UNITARIO
+TYPE(6) = IMPORTO
+LENGTH(6) = 9
+DECIMAL(6) = 3
+POSITION(6) = 61
+MESSAGE(6) = _RIGABOLLA,PREZZO
+
+NAME(7) = IMPORTO TOTALE
+TYPE(7) = IMPORTO
+LENGTH(7) = 9
+DECIMAL(7) = 3
+POSITION(7) = 70
+MESSAGE(7) = _RIGABOLLA,IMPORTO
+
+NAME(8) = NUMERO PEZZI
+TYPE(8) =
+LENGTH(8) = 4
+POSITION(8) = 79
+
+NAME(9) = TIPO IVA
+TYPE(9) = STRINGA
+LENGTH(9) = 1
+POSITION(9) = 83
+
+NAME(10) = ALIQUOTA IVA
+TYPE(10) = STRINGA
+LENGTH(10) = 2
+POSITION(10) = 84
+MESSAGE(10) = _RIGABOLLA,ALIQUOTA
+
+NAME(11) = TIPO MOVIMENTO
+TYPE(11) =
+LENGTH(11) = 1
+POSITION(11) = 86
+
+NAME(12) = TIPO CESSIONE
+TYPE(12) = STRINGA
+LENGTH(12) = 1
+POSITION(12) = 87
+MESSAGE(12) = _RIGABOLLA,OMAGGIO
+
+NAME(13) = NUMERO ORDINE CONAD
+TYPE(13) =
+LENGTH(13) = 6
+POSITION(13) = 88
+
+NAME(14) = CODICE LISTINO
+TYPE(14) =
+LENGTH(14) = 2
+POSITION(14) = 94
+
+NAME(15) = TIPO ARTICOLO
+TYPE(15) =
+LENGTH(15) = 1
+POSITION(15) = 96
+
+NAME(16) = TIPO CONTRATTO
+TYPE(16) =
+LENGTH(16) = 1
+POSITION(16) = 97
+
+NAME(17) = TIPO TRATTAMENTO
+TYPE(17) =
+LENGTH(17) = 1
+POSITION(17) = 98
+
+NAME(18) = COSTO TRASPORTO
+TYPE(18) =
+LENGTH(18) = 5
+DECIMAL(18) = 3
+POSITION(18) = 99
+
+NAME(19) = CODICE CONTABILE
+TYPE(19) =
+LENGTH(19) = 1
+POSITION(19) = 104
+
+NAME(20) = TIPO RESO
+TYPE(20) =
+LENGTH(20) = 1
+POSITION(20) = 105
+
+NAME(21) = PREZZO CATALOGO
+TYPE(21) =
+LENGTH(21) = 7
+DECIMAL(21) = 3
+POSITION(21) = 106
+
+NAME(22) = FILLER
+TYPE(22) =
+LENGTH(22) = 3
+POSITION(22) = 113
+
+NAME(23) = DATA ORDINE
+TYPE(23) =
+LENGTH(23) = 6
+POSITION(23) = 116
+
+NAME(24) = RISERVATO
+TYPE(24) =
+LENGTH(24) = 6
+POSITION(24) = 122
+
diff --git a/ve/opticpen.ini b/ve/opticpen.ini
index 201d49a3f..b4eb4d56f 100755
--- a/ve/opticpen.ini
+++ b/ve/opticpen.ini
@@ -15,4 +15,7 @@ LENGTH(2) = 5
 POSITION(0) = 0
 POSITION(1) = 13
 POSITION(2) = 15
+NAME(0) = CODART
+NAME(2) = QTA
+
 
diff --git a/ve/sconti.cpp b/ve/sconti.cpp
index fb33be54a..77680c52f 100755
--- a/ve/sconti.cpp
+++ b/ve/sconti.cpp
@@ -370,7 +370,7 @@ void TCond_vendita::ricerca(bool load_um_only, bool load_scagl_only)
     set_sconto("");  
     set_iva("");
     set_provv(ZERO);
-    if (!load_um_only && !load_scagl_only && prezzo_lordo)
+    if (prezzo_lordo)
       riga().set(FR_LORDO, "X");
     return;
   }            
@@ -389,7 +389,7 @@ void TCond_vendita::ricerca(bool load_um_only, bool load_scagl_only)
   const bool cv_scagl = _condv.get_bool("GESTSCAGL");
   const bool cv_um = _condv.get_bool("GESTUM");
 
-  if (!load_um_only && !load_scagl_only && prezzo_lordo)
+  if (prezzo_lordo)
     riga().set(FR_LORDO, "X");
 	else
 		riga().reset(FR_LORDO);
diff --git a/ve/ve1300.alx b/ve/ve1300.alx
index 50d8d8168..659b33108 100755
--- a/ve/ve1300.alx
+++ b/ve/ve1300.alx
@@ -21,6 +21,11 @@
   DOC_CLIENTE        \ user defined word in ve1.exe
 ;
 
+: MESSAGE_DITTA ( s1 -- )
+  GET_FIRM_DATA      \ user defined word in report
+;
+
+
 : MESSAGE_PARENTDOC ( [b1] s1 n1 -- )
   DOC_PARENT_DOC     \ user defined word in ve1.exe
 ;
@@ -39,4 +44,4 @@
 
 : MESSAGE_TOTIMPONIBILI ( [n1] -- )
   DOC_TOT_IMPONIBILI \ user defined word in ve1.exe
-;
+;
\ No newline at end of file
diff --git a/ve/ve1300.cpp b/ve/ve1300.cpp
index e0c923f87..4d1fb2c58 100755
--- a/ve/ve1300.cpp
+++ b/ve/ve1300.cpp
@@ -160,7 +160,7 @@ TDoc_recordset::~TDoc_recordset()
 class TReport_doc : public TReport
 {
   size_t _first_msg;
-//  TRelation _firmrel;
+
 
 protected:
   virtual void include_libraries(bool reload);
@@ -619,18 +619,11 @@ void TReport_doc::include_libraries(bool reload)
 }
 
 TReport_doc::TReport_doc(const char* name)
-//           : _firmrel(LF_NDITTE)
+
 { 
   // istanziamento e impostazione della relazione di gestione della ditta corrente
-//  _firmrel.add(LF_ANAG, "TIPOA=TIPOA|CODANAGR=CODANAGR");
-//  _firmrel.add(LF_UNLOC,"CODDITTA=CODDITTA"); // si posiziona sulla prima unita' locale della ditta//
-//  _firmrel.add(LF_COMUNI, "COM=STATORES+COMRES", 1, LF_ANAG, 100+LF_COMUNI);
-//  _firmrel.add(LF_COMUNI, "COM=STATORES+COMRF", 1, LF_ANAG, 200+LF_COMUNI);
-//  _firmrel.curr().put(NDT_CODDITTA, prefix().get_codditta());
-//  _firmrel.read();
-
-
   load(name); // Faccio la load altrimenti non include la libreria 1300.alx
+
 }
  
 TReport_doc::~TReport_doc()
@@ -668,6 +661,20 @@ public:
 
 bool TReport_doc_mask::on_field_event(TOperable_field& o, TField_event e, long jolly)
 {
+  switch (o.dlg())
+  {
+  case F_DA_NDOC:
+    if (e == fe_modify)
+    {
+      const long dal = get_long(F_DA_NDOC);
+      const long al = get_long(F_A_NDOC);
+      if (al < dal)
+        set(F_A_NDOC, dal);
+    }
+    break;
+  default:
+    break;
+  }
   return true;
 }
 
diff --git a/ve/ve2400.uml b/ve/ve2400.uml
index bd2eb2e34..b03fc8902 100755
--- a/ve/ve2400.uml
+++ b/ve/ve2400.uml
@@ -67,7 +67,7 @@ END
 
 BUTTON F_COPY 7 1
 BEGIN
-  PROMPT 68 1 "Copia"
+  PROMPT 68 1 "~Copia"
   FLAGS "H"
 END
 
diff --git a/ve/ve6500.cpp b/ve/ve6500.cpp
index 62ff51438..ad72c1af9 100755
--- a/ve/ve6500.cpp
+++ b/ve/ve6500.cpp
@@ -2,6 +2,7 @@
 #include <automask.h>
 #include <config.h>
 #include <filetext.h>
+#include <modaut.h>
 
 #include "../cg/cglib01.h"
 #include "../mg/mglib.h"
@@ -43,13 +44,11 @@ bool TPenna_mask::on_field_event(TOperable_field& f, TField_event e, long jolly)
     
       TFilename fname=f.get();         //se il nome del file non esiste -> gli assegna automaticamente il nome
       if(fname == "")                  //articoli.dat
-      {
-        fname = "articoli.dat";
-      }
+        fname = "articoli";
       
       xvt_fsys_get_dir(&dir);          //funzioni di xvt (grafica); utilizzate per creare la finestra di ricerca del
       xvt_fsys_get_dir(&fs.dir);       //file di tipo .dat (� una finestra tipo gestione risorse Windows)
-      strcpy(fs.type, fname.ext());
+      strcpy(fs.type, "dat");
       strcpy(fs.name, fname);
       strcpy(fs.creator, "ELD");
         
@@ -64,6 +63,8 @@ bool TPenna_mask::on_field_event(TOperable_field& f, TField_event e, long jolly)
       }
       
     }
+    if(e==fe_init && f.get().empty())                  
+			f.set("articoli.dat");
     if(e==fe_close)                //se e = alla pressione del bottone 'chiudi' (fe_close) controlla che il campo sia stato
     {                              //riempito correttamente nella maschera
       TFilename n=f.get();
@@ -71,6 +72,10 @@ bool TPenna_mask::on_field_event(TOperable_field& f, TField_event e, long jolly)
     }     
     break;
   
+  case F_TIPORIGA:                     
+    if(e==fe_init && f.get().empty())                  
+			f.set("01");
+    break;
   case F_TIPO:                        //scelta del tipo di registrazione
     if(e==fe_init || e==fe_modify)    
     {
@@ -119,8 +124,7 @@ TPenna_mask::TPenna_mask():TAutomask("ve6500")       //contructor di TPenna_mask
 {
   on_firm_change();                                  //chiama la funzione on_firm_change, che aggiorna in tutti i campi della
                                                      //maschera che fanno rif. ad una ditta, con il rif. alla ditta attuale
-}                                                    //In pratica resetta i campi della maschera, che potevano essere settati
-                                                     //precedentemente per un'altra ditta
+}
 
                                                      
 class TPenna_app : public TSkeleton_application
@@ -146,7 +150,7 @@ bool TPenna_app::load_ini()                           //definizione della member
   if (args <= 2)
     return FALSE;                                     //argv  � un array di null-terminated strings
 
-  const TString& arg = argv(2);
+	const TString& arg = argv(2);
   if ((arg[0] != '-' && arg[0] != '/') || (arg[1] != 'i' && arg[1] != 'I'))
     return FALSE;
     
@@ -176,7 +180,13 @@ bool TPenna_app::load_ini()                           //definizione della member
 
 
 void TPenna_app::main_loop()                              //definizione della member function main_loop, della classe TPenna_app
-{                 
+{              
+  if (!has_module(POAUT, CHK_DONGLE))
+	{
+    error_box("Modulo penna ottica non attivato");
+		return;
+	}
+
   if(! load_ini())
   {
     error_box("Impossibile aprire il file '%s'",(const char*)_ini_name); //mostra un messaggio di errore se non riesce ad aprire
@@ -206,10 +216,10 @@ void TPenna_app::main_loop()                              //definizione della me
                                                           
     TFile_text articoli(nomefile,"opticpen.ini");         //crea un oggetto articoli di tipo TFile_text
     TRecord_text articolocor;                             //crea un record vuoto con nome articolocor 
+		TTracciato_record & rec = *(articoli.t_rec(""));
+		const int nfields = rec.tracciati_campo().items();
     TString codice;                                       //crea una stringa per contenere il codice
 
-    real quantita;                                        //crea una variabile reale per contenere la quantita'; ovviamente
-                                                          //istanzio dalla classe real
     para.format("%d", LF_DOC);                             
     
     TDate datadoc(ini.get(DOC_DATADOC, para));      //dal paragrafo testata documento prende il valore della data del
@@ -224,39 +234,45 @@ void TPenna_app::main_loop()                              //definizione della me
     articoli.open();                                      //applico il metodo open che apre il file in lettura (contenuta in TFile_text)
     for(int i=_first_row;articoli.ok_r();i++)             //ok_r � una funzione che indica la fine del file
     { 
-      
       if(articoli.read(articolocor)==NOERR)
       { 
-        para.format("%d,%d", LF_RIGHEDOC,i);               // scrive i due numeri (%d) separati dalla , con format (che formatta
+	      para.format("%d,%d", LF_RIGHEDOC,i);               // scrive i due numeri (%d) separati dalla , con format (che formatta
                                                            // la stringa para con il formato specificato tra " ")
-        ini.set_paragraph(para);                           // sposta il cursore sulla nuova para (nuovo valore)
-        
-        
-        codice = articolocor.get(1);                     // assegno a codice il valore del primo campo; attraverso il .ini lui
-                                                         // sa gi� che sono i primi 15 caratteri del file; la funzione 
-                                                        // get(int pos) � in TRecord_text di Filetext.h assegno a quantita
-        quantita = real(articolocor.get(2));             // il valore del secondo campo del record; tutto il resto � come
-                                                         // sopra; poich� quantita � un real mentre get ritorna una stringa,
-                                                         // devo ridefinire localmente l'output di get, trasformandolo in 
-                                                         // real (operazione di cast)
-                                                           
-        if (tipo==1)
-        { 
+		    ini.set_paragraph(para);                           // sposta il cursore sulla nuova para (nuovo valore)
+				ini.set(RDOC_TIPORIGA,tiporiga);                                                            
+	      ini.set(RDOC_CODARTMAG, NULL_CODART);              // scrive il codice per forzare il check
+
+				for (int f = 0; f < nfields; f++)
+				{
+					const TTracciato_campo & c = rec.get(f);
+					const TString name = c.name();
+					if (name.not_empty())
+					{
+						TString val = articolocor.get(f);
+						val.trim();
+
+						if (name == RDOC_CODART)
+							codice = val;
+						else
+							if (name == RDOC_QTA && tipo==1)
+							{ 
           
-          TArticolo_giacenza art(codice);
-          const real giacenza=art.disponibilita(annoes,codmag,"",TRUE);
-          quantita = giacenza - quantita;
+								TArticolo_giacenza art(codice);
+								real quantita(val);
+
+								const real giacenza=art.disponibilita(annoes,codmag,"",TRUE);
+								quantita = giacenza - quantita;
+								val = quantita.string();			
+							}
+		        ini.set(name, val);                       // scrive il codice sul file ini
+					}
         }
-                                                           
-                                                                   
-        ini.set(RDOC_TIPORIGA,tiporiga);                                                            
-        ini.set(RDOC_CODART,codice);                       // scrive il codice sul file ini
-        ini.set(RDOC_CODARTMAG, NULL_CODART);              // scrive il codice per forzare il check
-        ini.set(RDOC_QTA,quantita.string());               // scrive la quantit� sul file ini dopo averla trasformata in stringa                               
       }                                                       
       else
         break;                           
-    }                                             
+    } 
+		articoli.close();
+		xvt_fsys_removefile(nomefile);
   }
      
 }  
@@ -266,6 +282,6 @@ void TPenna_app::main_loop()                              //definizione della me
 int ve6500(int argc, char** argv)
 {
   TPenna_app app;
-  app.run(argc,argv,"Penna Ottica");
+  app.run(argc,argv,"Terminali portatili");
   return 0;
 }
diff --git a/ve/ve6500.h b/ve/ve6500.h
index 255b13167..95b3a24c8 100755
--- a/ve/ve6500.h
+++ b/ve/ve6500.h
@@ -4,3 +4,4 @@
 #define F_MAG      104
 #define F_DEP      105
 #define F_DESCRMAG 106
+#define F_PROFILO  107
diff --git a/ve/ve6500.uml b/ve/ve6500.uml
index f840aafd3..70866f6c9 100755
--- a/ve/ve6500.uml
+++ b/ve/ve6500.uml
@@ -1,6 +1,6 @@
 #include "ve6500.h"
 
-PAGE "Lettura penna ottica" -1 -1 50 10
+PAGE "Lettura terminale portatile" -1 -1 80 12
 
 STRING F_FILE 128 40
 BEGIN
@@ -60,6 +60,12 @@ BEGIN
   GROUP 1       
 END
 
+STRING F_PROFILO 70 50
+BEGIN
+	PROMPT 1 -3 "Profilo "
+	PSELECT
+END
+
 BUTTON DLG_OK 10 2
 BEGIN
   PROMPT -12 -1 ""
diff --git a/ve/ve65f734a.PWT b/ve/ve65f734a.PWT
new file mode 100755
index 000000000..7f2c53f76
--- /dev/null
+++ b/ve/ve65f734a.PWT
@@ -0,0 +1 @@
+Formula 734
diff --git a/ve/ve65f734a.app b/ve/ve65f734a.app
new file mode 100755
index 000000000..eda6d672d
--- /dev/null
+++ b/ve/ve65f734a.app
@@ -0,0 +1,344 @@
+VERSION 1.0
+BEGIN Configuration
+   BaudRate                 = 53
+   DataBits                 = 49
+   Parity                   = 50
+   Comunication             = 49
+   Interface                = 49
+   ID                       = 1
+   Delay                    = 0
+   CheckSum                 = 49
+   SOB                      = 34
+   EOB                      = 45
+   EOT                      = 35
+   MessageRow1              =     DATALOGIC
+   MessageRow2              =      EASYGEN
+   MessageRow3              =    Acquisizione
+   MessageRow4              =      Articoli
+   Intensity                = 51
+   Note                     = 52
+   Period                   = 49
+END
+BEGIN Register
+   Name                     = Error
+END
+BEGIN Register
+   Name                     = Variable 2
+END
+BEGIN Register
+   Name                     = Variable 3
+END
+BEGIN Register
+   Name                     = Variable 4
+END
+BEGIN Register
+   Name                     = Variable 5
+END
+BEGIN Register
+   Name                     = Variable 6
+END
+BEGIN Register
+   Name                     = Variable 7
+END
+BEGIN Table
+   Name                     = articoli
+   MaxRecords               = 500
+   BEGIN Field
+      Name                     = Codice
+      FieldType                = 0
+      Size                     = 20
+      Alignment                = 49
+      Fill                     = 32
+      CharacterFrom            = 32
+      CharacterTo              = 122
+   END
+   BEGIN Field
+      Name                     = Quantita
+      FieldType                = 0
+      Size                     = 15
+      Alignment                = 48
+      Fill                     = 32
+      CharacterFrom            = 32
+      CharacterTo              = 122
+   END
+END
+BEGIN Table
+   Name                     = EAN128tb
+   MaxRecords               = 1
+   BEGIN Field
+      Name                     = Campo1
+      FieldType                = 0
+      Size                     = 32
+      Alignment                = 49
+      Fill                     = 32
+      CharacterFrom            = 32
+      CharacterTo              = 122
+   END
+END
+BEGIN Function
+   Label                    = Inizio e Cancellazione Display
+   BEGIN Clear
+   END
+END
+BEGIN Function
+   Label                    = Inserimento barcode e Memorizzazione nel campo "Codice"
+   BEGIN InputBarcode
+      Col                      = 1
+      Row                      = 1
+      Label                    = Codice : 
+      Standard39               = False
+      Standard39Size1          = 0
+      Standard39Size2          = 0
+      Standard39Size3          = 0
+      Standard39CheckDigit     = False
+      Interleaved25            = True
+      Interleaved25Size1       = 0
+      Interleaved25Size2       = 0
+      Interleaved25Size3       = 0
+      Interleaved25CheckDigit  = False
+      Matrix25                 = True
+      Matrix25Size1            = 0
+      Matrix25Size2            = 0
+      Matrix25Size3            = 0
+      Matrix25CheckDigit       = False
+      DeltaAIBM                = False
+      DeltaAIBMSize1           = 0
+      DeltaAIBMSize2           = 0
+      DeltaAIBMSize3           = 0
+      DeltaAIBMCheckDigit      = False
+      MSI                      = False
+      MSISize1                 = 0
+      MSISize2                 = 0
+      MSISize3                 = 0
+      MSICheckDigit            = False
+      Extended39               = True
+      Extended39Size1          = 0
+      Extended39Size2          = 0
+      Extended39Size3          = 0
+      PharmaIt                 = False
+      PharmaItSize1            = 0
+      PharmaItSize2            = 0
+      PharmaItSize3            = 0
+      PharmaFr                 = False
+      PharmaFrSize1            = 0
+      PharmaFrSize2            = 0
+      PharmaFrSize3            = 0
+      ITF14                    = False
+      ITF14Size1               = 0
+      ITF14Size2               = 0
+      ITF14Size3               = 0
+      Industrial25             = True
+      Industrial25Size1        = 0
+      Industrial25Size2        = 0
+      Industrial25Size3        = 0
+      Monarch27                = True
+      Monarch27Size1           = 0
+      Monarch27Size2           = 0
+      Monarch27Size3           = 0
+      NW7                      = False
+      NW7Size1                 = 0
+      NW7Size2                 = 0
+      NW7Size3                 = 0
+      Pako                     = False
+      PakoSize1                = 0
+      PakoSize2                = 0
+      PakoSize3                = 0
+      Code128                  = True
+      Code128Size1             = 0
+      Code128Size2             = 0
+      Code128Size3             = 0
+      Code93                   = True
+      Code93Size1              = 0
+      Code93Size2              = 0
+      Code93Size3              = 0
+      UpcEan                   = True
+      UpcEanSize1              = 0
+      UpcEanSize2              = 0
+      UpcEanSize3              = 0
+      UpcOnly                  = False
+      UpcOnlySize1             = 0
+      UpcOnlySize2             = 0
+      UpcOnlySize3             = 0
+      UpcAEan13                = False
+      UpcAEan13Size1           = 0
+      UpcAEan13Size2           = 0
+      UpcAEan13Size3           = 0
+      Ean8Only                 = False
+      Ean8OnlySize1            = 0
+      Ean8OnlySize2            = 0
+      Ean8OnlySize3            = 0
+      UpcEOnly                 = False
+      UpcEOnlySize1            = 0
+      UpcEOnlySize2            = 0
+      UpcEOnlySize3            = 0
+      UpcEan2D                 = False
+      UpcEan2DSize1            = 0
+      UpcEan2DSize2            = 0
+      UpcEan2DSize3            = 0
+      UpcEan5D                 = False
+      UpcEan5DSize1            = 0
+      UpcEan5DSize2            = 0
+      UpcEan5DSize3            = 0
+      UpcB                     = False
+      UpcBSize1                = 0
+      UpcBSize2                = 0
+      UpcBSize3                = 0
+      UpcAPlus0                = False
+      UpcAPlus0Size1           = 0
+      UpcAPlus0Size2           = 0
+      UpcAPlus0Size3           = 0
+      UpcEWithout0             = False
+      UpcEWithout0Size1        = 0
+      UpcEWithout0Size2        = 0
+      UpcEWithout0Size3        = 0
+      Zellweger                = True
+      ZellwegerSize1           = 0
+      ZellwegerSize2           = 0
+      ZellwegerSize3           = 0
+      Flag                     = 1
+      Table                    = 1
+      Field                    = 1
+      Register                 = 1
+      Exception                = False
+      ExceptionKey             = 0
+      JumpTo                   = 
+   END
+END
+BEGIN Function
+   Label                    = Beep per Codice OK
+   BEGIN Beep
+      Intensity                = 144
+      Note                     = 64
+      Period                   = 50
+   END
+END
+BEGIN Function
+   Label                    = Operazione aritmetica1
+   BEGIN Operation
+      Flag1                    = 1
+      Flag2                    = 0
+      Flag3                    = 0
+      Label2                   = 1
+      Label3                   = 
+      Table1                   = 1
+      Table2                   = 1
+      Table3                   = 1
+      Field1                   = 2
+      Field2                   = 1
+      Field3                   = 1
+      Register1                = 1
+      Register2                = 1
+      Register3                = 1
+      Index1                   = 1
+      Index2                   = 1
+      Index3                   = 1
+      Operation                = 2
+      OperationNumKey          = 49
+      OperationStrKey          = 49
+      SezStr                   = False
+      FirstPosiz               = 1
+      LastPosiz                = 1
+   END
+END
+BEGIN Function
+   Label                    = Inserimento quantit� e Memorizzazione nel campo "Quantita"
+   BEGIN InputText
+      Col                      = 1
+      Row                      = 3
+      Label                    = Q.ta   : 
+      Size                     = 15
+      Flag                     = 2
+      Table                    = 1
+      Field                    = 2
+      Register                 = 2
+      Exception                = True
+      ExceptionKey             = 4
+      JumpTo                   = Inizio e Cancellazione Display
+   END
+END
+BEGIN Function
+   Label                    = Beep per Quantity OK
+   BEGIN Beep
+      Intensity                = 144
+      Note                     = 64
+      Period                   = 50
+   END
+END
+BEGIN Function
+   Label                    = Confronto1
+   BEGIN IfThen
+      Flag1                    = 2
+      Flag2                    = 0
+      Label1                   = 
+      Label2                   = 
+      Table1                   = 1
+      Table2                   = 1
+      Field1                   = 2
+      Field2                   = 1
+      Register1                = 2
+      Register2                = 1
+      Index1                   = 1
+      Index2                   = 1
+      Compare                  = 1
+      CompareNumKey            = 48
+      CompareStrKey            = 48
+      JumpToTrue               = Acquisizione testo1
+      JumpToFalse              = Memorizzazione quantita
+   END
+END
+BEGIN Function
+   Label                    = Memorizzazione quantita
+   BEGIN Operation
+      Flag1                    = 1
+      Flag2                    = 2
+      Flag3                    = 0
+      Label2                   = 
+      Label3                   = 
+      Table1                   = 1
+      Table2                   = 1
+      Table3                   = 1
+      Field1                   = 2
+      Field2                   = 1
+      Field3                   = 1
+      Register1                = 1
+      Register2                = 2
+      Register3                = 1
+      Index1                   = 1
+      Index2                   = 1
+      Index3                   = 1
+      Operation                = 2
+      OperationNumKey          = 49
+      OperationStrKey          = 49
+      SezStr                   = False
+      FirstPosiz               = 1
+      LastPosiz                = 1
+   END
+END
+BEGIN Function
+   Label                    = Acquisizione testo1
+   BEGIN InputText
+      Col                      = 13
+      Row                      = 4
+      Label                    = Ok
+      Size                     = 32
+      Flag                     = 2
+      Table                    = 1
+      Field                    = 1
+      Register                 = 2
+      Exception                = True
+      ExceptionKey             = 4
+      JumpTo                   = Inizio e Cancellazione Display
+   END
+END
+BEGIN Function
+   Label                    = Punta al prossimo record e Ricomincia
+   BEGIN Loop
+      JumpTo                   = Inizio e Cancellazione Display
+      Increase1                = True
+      Increase2                = False
+      Increase3                = False
+      Table1                   = 1
+      Table2                   = 0
+      Table3                   = 0
+   END
+END
diff --git a/ve/ve6f734a.ini b/ve/ve6f734a.ini
new file mode 100755
index 000000000..153391b82
--- /dev/null
+++ b/ve/ve6f734a.ini
@@ -0,0 +1,15 @@
+[MAIN]
+DECSEP = 
+FIELDSEP = |
+RECORDSEP = 
+RECORDSIZE =
+SKIPLINES = 0
+TYPEFIELD = -1
+TYPELEN = 0
+TYPEPOS = -1
+
+[RECORD]
+LENGTH(0) = 20
+LENGTH(1) = 8
+NAME(0) = CODART
+NAME(1) = QTA
\ No newline at end of file
diff --git a/ve/ve7400.cpp b/ve/ve7400.cpp
index 4ef341bed..9cbb49758 100755
--- a/ve/ve7400.cpp
+++ b/ve/ve7400.cpp
@@ -61,6 +61,7 @@ class TBolle2Conad : public TSkeleton_application
   TRiga_documento*   _rigabolla;
   TFilConad*				 _trasfile;
   long							 _progressivo;
+  int								 _modalita;     // 0 = elabora doc. originali (MARPESCA) 1 = elabora doc. indicati (MAINARDI)
   TAssoc_array*			 _elencobolle; // assoc array per verificare se la bolla � gia stat passata
   
 protected:
@@ -139,6 +140,15 @@ void TFilConad::validate(TCursor& cur,TRecord_text &rec, TToken_string &s, TStri
     	valore = data.string(brief, '-', full, full, amg_date);
     	valore.strip("-");
     }
+		else if (in == "NUMERO")
+		{
+			valore = str;
+			const TString16 codnum = cur.curr().get("CODNUM");
+			TString16 suffisso = cache().get("%NUM", codnum, "S7");
+			valore.trim();
+			suffisso.trim();
+			valore << suffisso;
+		}
   }
   else if (code == "_RIGABOLLA")
   {
@@ -182,7 +192,7 @@ void TFilConad::validate(TCursor& cur,TRecord_text &rec, TToken_string &s, TStri
 
 bool TBolle2Conad::create()
 {      
-	open_files(LF_DOC, LF_RIGHEDOC, LF_CLIFO, LF_CFVEN, LF_ANAMAG, 0);
+	open_files(LF_DOC, LF_RIGHEDOC, LF_CLIFO, LF_CFVEN, LF_INDSP, LF_ANAMAG, 0);
   _msk = new TBolle2Conad_mask();
   _trasfile = NULL;
 	_elencobolle = new TAssoc_array();
@@ -203,6 +213,8 @@ bool TBolle2Conad::destroy()
 void TBolle2Conad::main_loop()
 {
 	TConfig config("ve7400a.ini", "TRASFERIMENTO");
+	TFilename tracciatoname = config.get("TRACCIATO");
+	_modalita = config.get_int("MODALITA");
 	_codconad = config.get_long("CONAD");
 	_codforn = config.get("FORNITORE");
 	TFilename filename = config.get("NOMEFILE");
@@ -212,7 +224,7 @@ void TBolle2Conad::main_loop()
   {                     
 		_elencobolle->destroy();
   	_progressivo = 0;
-  	_trasfile = new TFilConad(filename, "filconad.ini");
+  	_trasfile = new TFilConad(filename, tracciatoname);
   	_trasfile->open(filename,'w');
 	   _trasfile->force_record_separator(TRUE);
   	
@@ -231,26 +243,39 @@ void TBolle2Conad::elabora_documenti()
 
   TRelation doc_rel(LF_DOC);
   doc_rel.add(LF_RIGHEDOC, "CODNUM==CODNUM|ANNO==ANNO|PROVV==PROVV|NDOC==NDOC");
+  doc_rel.add(LF_CFVEN, "TIPOCF==TIPOCF|CODCF==CODCF");
   TRectype da(LF_DOC);
   TRectype a(LF_DOC);
   const long items = sheet.items();
   if (items > 0)
   {
+	  bool ok = TRUE;
 	  TString16 codnum;
 	  TString filt_expr;
+	  if (_modalita == 0) // MARPESCA, seleziono in base al codice cliente indicato in ve7400a.ini
+	  {
+			da.put("TIPOCF", "C");
+			da.put("CODCF", _codconad);
+			da.put("PROVV", "D");
+			da.put("ANNO", _dataini.year());
+			da.put("DATADOC", _dataini);
 
-	  da.put("TIPOCF", "C");
-	  da.put("CODCF", _codconad);
-	  da.put("PROVV", "D");
-	  da.put("ANNO", _dataini.year());
-	  da.put("DATADOC", _dataini);
-
-	  a.put("TIPOCF", "C");
-	  a.put("CODCF", _codconad);
-	  a.put("PROVV", "D");
-	  a.put("ANNO", _datafin.year());
-	  a.put("DATADOC", _datafin);
+			a.put("TIPOCF", "C");
+			a.put("CODCF", _codconad);
+			a.put("PROVV", "D");
+			a.put("ANNO", _datafin.year());
+			a.put("DATADOC", _datafin);
+		}
+		else // MAINARDI selezione solo per data iniziale e finale
+		{
+		  da.put("DATADOC", _dataini);
+		  da.put("PROVV", "D");
+		  da.put("ANNO", _dataini.year());
 	  
+		  a.put("DATADOC", _datafin);
+		  a.put("PROVV", "D");
+		  a.put("ANNO", _datafin.year());
+		}
 	  filt_expr << "(";
 	  FOR_EACH_SHEET_ROW(sheet, r, row)
 	  {
@@ -263,14 +288,30 @@ void TBolle2Conad::elabora_documenti()
 	  }
 	  filt_expr.rtrim(2);  
 	  filt_expr << ")";
-	
+    if (_modalita == 0)
 	  _cur = new TCursor(&doc_rel,filt_expr,2,&da,&a);
+	  else
+	  	_cur = new TCursor(&doc_rel,filt_expr,3,&da,&a);
 	  const long cur_items = _cur ->items(); // Scorre tutti i documenti che rientrano nell'intervallo selezionato
 	  if (cur_items != 0) 
 	  {
 		  _cur->freeze();
+	    TRectype& cur_rec = _cur->curr();
 	    for (*_cur = 0; _cur->pos() < cur_items; ++(*_cur))
-	    	elabora_righe_doc();
+	    {
+	    	if (_modalita == 0)
+		    	elabora_righe_doc();
+	    	else                      
+	    	{
+	    		TString16 codprcf = _cur->curr(LF_CFVEN).get("CODPRCF");
+	    		if (codprcf.not_empty())
+	    		{
+						_bolla = new TDocumento(_cur->curr());
+						elabora_doc_originale(*_bolla);
+						delete _bolla;
+					}
+				}
+			}
 	  }                  
 	  delete _cur;
 	}  
@@ -312,8 +353,9 @@ void TBolle2Conad::elabora_doc_originale(const TDocumento& documento)
   bol_rel.add(LF_RIGHEDOC, "CODNUM==CODNUM|ANNO==ANNO|PROVV==PROVV|NDOC==NDOC");
   bol_rel.add(LF_ANAMAG, "CODART==CODART", 1, LF_RIGHEDOC);
   bol_rel.add(LF_INDSP, "TIPOCF==TIPOCF|CODCF==CODCF|CODIND==CODINDSP", 1, LF_DOC);
+  bol_rel.add(LF_CFVEN, "TIPOCF==TIPOCF|CODCF==CODCF",1, LF_DOC);
+	TRectype da(documento.head());
   
-  TRectype da(documento.head());
   TCursor bol_cur(&bol_rel, "", 2, &da, &da);
   bol_cur = 0;
 	_progressivo++;                   	
diff --git a/ve/ve7400a.h b/ve/ve7400a.h
index 4474221ce..5ef9c1cda 100755
--- a/ve/ve7400a.h
+++ b/ve/ve7400a.h
@@ -6,5 +6,3 @@
 // campi dello sheet
 #define F_S_CODNUM      101
 #define F_S_DESNUM      102
-//#define F_S_TIPODOC     103
-//#define F_S_DESTIPO     104
diff --git a/ve/ve7400a.uml b/ve/ve7400a.uml
index 34ffdb294..af3533c26 100755
--- a/ve/ve7400a.uml
+++ b/ve/ve7400a.uml
@@ -1,6 +1,6 @@
 #include "ve7400a.h"
 
-TOOLBAR "" 0 -3 0 3
+TOOLBAR "" 0 -5 0 4
 
 STRING 30 70 50
   BEGIN
@@ -11,12 +11,12 @@ END
 
 BUTTON DLG_OK 10 2
 BEGIN
-  PROMPT -12 -1 ""
+  PROMPT -12 -11 ""
 END
 
 BUTTON DLG_QUIT 10 2
 BEGIN
-  PROMPT -22 -1 ""
+  PROMPT -22 -11 ""
 END
 
 ENDPAGE
@@ -51,7 +51,7 @@ END
 
 DATE F_DATAINI
 BEGIN
-  PROMPT 2 4 "Fatture dal "
+  PROMPT 2 4 "Documenti dal "
   HELP "Data di inizio per trasferimento documenti"
   CHECKTYPE REQUIRED
   WARNING "Data dal non valida"
@@ -60,20 +60,18 @@ END
 
 DATE F_DATAFIN
 BEGIN
-  PROMPT 30 4 "al "
+  PROMPT 32 4 "al "
   HELP "Data di fine per trasferimento documenti"
   CHECKTYPE REQUIRED
   VALIDATE DATE_CMP_FUNC >= F_DATAINI
   WARNING "Data di fine scadenza non valida"
 END
 
-SPREADSHEET F_SHEETDOC 78 14
+SPREADSHEET F_SHEETDOC 78 10
 BEGIN
    PROMPT 1 6 "Scelta documenti"
    ITEM "Cod. num."
    ITEM "Descrizione num.@50"
-   //ITEM "Tipo doc."
-   //ITEM "Descrizione tipo@45"
 END
 
 ENDPAGE
@@ -105,31 +103,6 @@ BEGIN
    COPY OUTPUT F_S_CODNUM
 END
 
-//STRING F_S_TIPODOC 4
-//BEGIN
-//   PROMPT 2 2 "Tipo doc. "
-//   HELP "Codice tipo documento"
-//   USE %TIP
-//   INPUT CODTAB F_S_TIPODOC
-//   DISPLAY "Codice" CODTAB
-//   DISPLAY "Descrizione@50" S0
-//   OUTPUT F_S_TIPODOC CODTAB
-//   OUTPUT F_S_DESTIPO S0
-//   CHECKTYPE REQUIRED
-//   FLAG "UP"
-//END
-
-//STRING F_S_DESTIPO 50
-//BEGIN
-//   PROMPT 20 2 ""
-//   HELP "Descrizione tipo documento"
-//   USE %TIP KEY 2
-//   INPUT S0 F_S_DESTIPO
-//   DISPLAY "Descrizione@50" S0
-//   DISPLAY "Codice" CODTAB
-//   COPY OUTPUT F_S_TIPODOC
-//END
-
 BUTTON DLG_OK 9 2
 BEGIN
  PROMPT -13 -1 ""
diff --git a/ve/velib.h b/ve/velib.h
index 729b386be..764721126 100755
--- a/ve/velib.h
+++ b/ve/velib.h
@@ -484,7 +484,7 @@ public:
   bool sola_descrizione() const;
   void forza_sola_descrizione();
   
-  void set_original_rdoc_key(const TRectype& orig);
+  void set_original_rdoc_key(const TRectype& orig, int depth = 0);
   void reset_original_rdoc_key();
   const TRectype* find_original_rdoc() const;
   
@@ -854,7 +854,6 @@ public:
   virtual ~TDocumento_mask();
 };
 
-
 struct dec_parm {
   int qta_lit, 
       qta_val;
diff --git a/ve/velib02.cpp b/ve/velib02.cpp
index bb882e6f4..049923841 100755
--- a/ve/velib02.cpp
+++ b/ve/velib02.cpp
@@ -402,10 +402,11 @@ bool TRiga_documento::raggruppabile(const TRiga_documento& r, TToken_string& cam
 TRiga_documento& TRiga_documento::operator +=(const TRiga_documento& r)
 { 
   const TTipo_documento& tipo = doc().tipo();
+
+/* Jurassic mode
   TToken_string campi("NCOLLI");
   campi.add(tipo.field_qta());
   campi.add(tipo.field_qtaevasa());
-  
   for (const char* c = campi.get(0); c; c = campi.get())
   {
     real num = r.get_real(c);
@@ -415,6 +416,12 @@ TRiga_documento& TRiga_documento::operator +=(const TRiga_documento& r)
       put(c, num);
     }  
   }   
+*/
+  // New age mode
+  const char* const campi[5] = { RDOC_NCOLLI, RDOC_TARA, RDOC_PNETTO, tipo.field_qta(), tipo.field_qtaevasa() };
+  for (int i = 0; i < 5; i++)
+    add(campi[i], r.get_real(campi[i]));
+
   if (!get_bool("RIGAEVASA"))
   {      
     if (qtaresidua().is_zero()) // same as is_evasa()
@@ -1010,14 +1017,30 @@ TArticolo_giacenza * TRiga_documento::articolo() const
   return &(_articoli->art(codart));     
 }
 
-void TRiga_documento::set_original_rdoc_key(const TRectype& orig)
+void TRiga_documento::set_original_rdoc_key(const TRectype& orig, int depth)
 {
   CHECK(orig.num() == LF_RIGHEDOC, "Bad document row");
-  put(RDOC_DACODNUM, orig.get(RDOC_CODNUM));
-  put(RDOC_DAANNO,   orig.get(RDOC_ANNO));
-  put(RDOC_DAPROVV,  orig.get(RDOC_PROVV));
-  put(RDOC_DANDOC,   orig.get(RDOC_NDOC));
-  put(RDOC_DAIDRIGA, orig.get(RDOC_IDRIGA));
+
+  switch (depth)
+  {
+  case 0:
+    put(RDOC_DACODNUM, orig.get(RDOC_CODNUM));
+    put(RDOC_DAANNO,   orig.get(RDOC_ANNO));
+    put(RDOC_DAPROVV,  orig.get(RDOC_PROVV));
+    put(RDOC_DANDOC,   orig.get(RDOC_NDOC));
+    put(RDOC_DAIDRIGA, orig.get(RDOC_IDRIGA));
+    break;
+  case 1:
+    put(RDOC_DACODNUM, orig.get(RDOC_DACODNUM));
+    put(RDOC_DAANNO,   orig.get(RDOC_DAANNO));
+    put(RDOC_DAPROVV,  orig.get(RDOC_DAPROVV));
+    put(RDOC_DANDOC,   orig.get(RDOC_DANDOC));
+    put(RDOC_DAIDRIGA, orig.get(RDOC_DAIDRIGA));
+    break;
+  default:
+    CHECK(0, "Sorry, too deep!");
+    break;
+  }
 }
 
 void TRiga_documento::reset_original_rdoc_key()
diff --git a/ve/velib03.cpp b/ve/velib03.cpp
index 2565d80a5..73d7d2816 100755
--- a/ve/velib03.cpp
+++ b/ve/velib03.cpp
@@ -1019,19 +1019,24 @@ int TDocumento::write_rewrite(TBaseisamfile & f, bool re) const
     for (int i = rows; i > 0; i--)
     {
       TRiga_documento& r = myself.row(i);
-      if ((r.is_merce() || r.is_omaggio()) && !r.is_checked() && r.get("CODARTMAG") != NULL_CODART)
-      {                         
-        const TString & codart = r.get("CODART");
-        anamag.put("CODART", codart);
-        if (anamag.read() == NOERR)
-          r.put("CODARTMAG", codart);
-         else
-        {
-          codalt.put("CODARTALT", codart);
-          if (codalt.read() == NOERR)
-            r.put("CODARTMAG", codalt.get("CODART"));
-        }
-        r.checked();
+      if ((r.is_merce() || r.is_omaggio()) && !r.is_checked())
+      { 
+				if (r.get(RDOC_CODARTMAG) == NULL_CODART)
+					r.put(RDOC_CODARTMAG, "");
+				else
+				{
+					const TString & codart = r.get("CODART");
+					anamag.put("CODART", codart);
+					if (anamag.read() == NOERR)
+						r.put("CODARTMAG", codart);
+					 else
+					{
+						codalt.put("CODARTALT", codart);
+						if (codalt.read() == NOERR)
+							r.put("CODARTMAG", codalt.get("CODART"));
+					}
+					r.checked();
+				}
       }
       if (r.is_evadibile() && is_ordine())
       {
@@ -1164,7 +1169,7 @@ int TDocumento::remove(TBaseisamfile& f) const
 
 int TDocumento::decimals(bool price) const
 {                               
-  const TString& codval = get(DOC_CODVAL);
+  const TString4 codval(get(DOC_CODVAL));
   const TExchange exc(codval);
   const int ndec = exc.decimals(price);
   return ndec;
@@ -1491,34 +1496,36 @@ void TDocumento::set_fields(TAuto_variable_rectype & rec)
     for (const TFormula_documento* f = tipo_doc.first_formula(); f; f = tipo_doc.succ_formula())
     {     
       TExpr_documento * exp = f->expr(); 
-      if (tot_doc == f->name())
-      {   
-        TString16 tot_doc_netto(tot_doc);
-        tot_doc_netto.insert("_");                          
+      if (exp != NULL) // Puo' succedere che sia NULL con dati incoerenti
+      {
+        if (tot_doc == f->name())
+        {   
+          TString16 tot_doc_netto(tot_doc);
+          tot_doc_netto.insert("_");                          
 
-        const TFixed_string netto_def(exp->string());              
-        TExpr_documento netto_exp(netto_def, _numexpr, this);
+          const TFixed_string netto_def(exp->string());              
+          TExpr_documento netto_exp(netto_def, _numexpr, this);
                                            
-        add_field(new TDocumento_variable_field(tot_doc_netto, netto_exp));
+          add_field(new TDocumento_variable_field(tot_doc_netto, netto_exp));
         
-        if (netto_def == "IMPONIBILI()+IMPOSTE()")
-        {
-          TExpr_documento tot_exp("IMPONIBILI(1)+IMPOSTE(1)", _numexpr, this);
-          add_field(new TDocumento_variable_field(tot_doc, tot_exp));
+          if (netto_def == "IMPONIBILI()+IMPOSTE()")
+          {
+            TExpr_documento tot_exp("IMPONIBILI(1)+IMPOSTE(1)", _numexpr, this);
+            add_field(new TDocumento_variable_field(tot_doc, tot_exp));
+          }
+          else
+          {
+            TExpr_documento tot_exp(format("%s + _BOLLI(%s)", (const char *) tot_doc_netto,
+                                           (const char *) tot_doc_netto), _numexpr, this);
+            add_field(new TDocumento_variable_field(tot_doc, tot_exp));
+          }
         }
         else
-        {
-          TExpr_documento tot_exp(format("%s + _BOLLI(%s)", (const char *) tot_doc_netto,
-                                         (const char *) tot_doc_netto), _numexpr, this);
-          add_field(new TDocumento_variable_field(tot_doc, tot_exp));
-        }
-      }
-      else
-        if (exp)
         {
           exp->set_doc(this);     
           add_field(new TDocumento_variable_field(f->name(), *exp));
         }
+      }
     }                      
   }
 }
diff --git a/ve/velib04.h b/ve/velib04.h
index 4f4fb39d6..aa690cc40 100755
--- a/ve/velib04.h
+++ b/ve/velib04.h
@@ -442,6 +442,9 @@ public:
 
 class TConsuntivazione_produzione : public TElaborazione  // velib04e
 { 
+protected:
+	bool ref2doc(char & provv, int & anno, TString8 & codnum, long & ndoc, int & nriga, const TString & codart);
+
 public:
   virtual bool elabora(TLista_documenti& doc_in, TLista_documenti& doc_out,
                        const TDate& data_elab, bool interattivo = FALSE);
diff --git a/ve/velib04a.cpp b/ve/velib04a.cpp
index 6add29e73..fed3086ac 100755
--- a/ve/velib04a.cpp
+++ b/ve/velib04a.cpp
@@ -192,6 +192,11 @@ bool TFatturazione_bolle::raggruppa(TDocumento& doc_in, TDocumento& doc_out)
 				rout.zero(RDOC_QTAEVASA);
 				rout.zero(RDOC_RIGAEVASA);
 			}
+      if (kill_descrizione_estesa())             // Cancello eventualmente la descrizione estesa
+      {
+        rout.zero(RDOC_DESCLUNGA);
+        rout.zero(RDOC_DESCEST);
+      }
 
 			if (prezzo_da_ordine())  // Se devo copiare il prezzo originale all'ordine
 			{
@@ -328,15 +333,9 @@ bool TFatturazione_bolle::elabora(TLista_documenti& doc_in, TLista_documenti& do
     const TString16 tipo_cli(cfven.get(CFV_TIPODOCFAT)); 
 
     TRecfield td(d, DOC_TIPODOC);                      // Uso il TRecfield per scavalcare tutti gli automatismi
-#ifdef  DBG
-    real tot = d.totale_doc();
-#endif    
     td = tipo_cli.empty() ? tipo_out : tipo_cli;
     TString16 sconto(d.get(DOC_SCONTOPERC));
     d.put(DOC_SCONTOPERC, sconto);
-#ifdef  DBG
-    tot = d.totale_doc();
-#endif    
   }
   return tot > 0;
 }
diff --git a/ve/velib04b.cpp b/ve/velib04b.cpp
index 09a5193dd..8e2a6fbd7 100755
--- a/ve/velib04b.cpp
+++ b/ve/velib04b.cpp
@@ -140,6 +140,7 @@ int TMovimentoPN_VE::set_cg_rec(int n, const TImporto& imp, const TBill& conto,
   rec.put(RMV_SEZIONE,imp.sezione());
   rec.put(RMV_IMPORTO,imp.valore());
   conto.put(rec);
+
   rec.put(RMV_DESCR, desc);
   
   if (tipo != ' ')
@@ -1578,8 +1579,8 @@ error_type TContabilizzazione::search_costo_ricavo(TBill& conto, const TRiga_doc
   
   switch (t)
   {
-    case 'O': // righe omaggio come articoli spiaccicato identico (avranno imponibile 0)
-    case 'M': // righe di merce
+    case RIGA_OMAGGI: // righe omaggio come articoli spiaccicato identico (avranno imponibile 0)
+    case RIGA_MERCE: // righe di merce
     {
       // posiziona l'anagrafica sull'articolo specificato sulla ..iga
       _anamag->put(ANAMAG_CODART,r.get(RDOC_CODART));
@@ -1674,50 +1675,72 @@ error_type TContabilizzazione::search_costo_ricavo(TBill& conto, const TRiga_doc
       }
       break; // case 'M'
     }
-    case 'P': // righe prestazione 
-    case 'S': // righe spese
+    case RIGA_PRESTAZIONI: // righe prestazione 
+    case RIGA_SPESEDOC: // righe spese
     {
-      TTable*  tab = t == 'P' ? _prs : _spp;
-      tab->put("CODTAB",r.get(RDOC_CODART));
-      if (tab->read()==NOERR)
-      {
-        gr = tab->get_int(is_cli ? "I0" : "I3");
-        co = tab->get_int(is_cli ? "I1" : "I4");
-        so = tab->get_long(is_cli ? "I2" : "I5");
-        conto.set(gr,co,so);                    
-        if (!is_cli && !conto.ok())
-        {
-          gr = r.get_int("QTAGG1");
-          co = r.get_int("QTAGG2");
-          so = r.get_long("QTAGG3");
-          conto.set(gr,co,so);                    
-        }
-      }
-      
-      if (!conto.find() && t == 'P') // Cerca il conto nella stringa di ricerca (solo per prestazioni)
-      {
-        TString16 tok;
-        // Scorre la stringa di ricerca ma solo per causale o CLI/FO
-        for (int i=0;good() && i<items;i++)
-        { 
-          tok = _search_seq->get(i);
-          if (tok == "CF")
-          {
-            if (skip_clifo) continue;
-            gr = cli_file.get_int(CLI_GRUPPORIC);
-            co = cli_file.get_int(CLI_CONTORIC);
-            so = cli_file.get_long(CLI_SOTTOCRIC);
-            conto.set(gr,co,so);
-            if (conto.ok()) break;
-          }
-          else
-            if (tok == "CA")
-            {
-              CHECK(_caus,"Causale documento non valida");
-              if (_caus->IVA2bill(codiva,conto)) break;
-            }
-        }
-      }
+			const TSpesa_prest & spesa = r.spesa();
+
+      gr = spesa.get_int(is_cli ? "I0" : "I3");
+      co = spesa.get_int(is_cli ? "I1" : "I4");
+      so = spesa.get_long(is_cli ? "I2" : "I5");
+      conto.set(gr,co,so);                    
+      if (!conto.ok())
+			{
+				gr = r.get_int("QTAGG1");
+				co = r.get_int("QTAGG2");
+				so = r.get_long("QTAGG3");
+				conto.set(gr,co,so);                    
+	    
+				if (!conto.ok()) // Cerca il conto nella stringa di ricerca (solo per prestazioni)
+				{
+					if (t == RIGA_PRESTAZIONI) // Cerca il conto nella stringa di ricerca (solo per prestazioni)
+					{
+						TString16 tok;
+						// Scorre la stringa di ricerca ma solo per causale o CLI/FO
+						for (int i=0;good() && i<items;i++)
+						{ 
+							tok = _search_seq->get(i);
+							if (tok == "CF")
+							{
+								if (skip_clifo) continue;
+								gr = cli_file.get_int(CLI_GRUPPORIC);
+								co = cli_file.get_int(CLI_CONTORIC);
+								so = cli_file.get_long(CLI_SOTTOCRIC);
+								conto.set(gr,co,so);
+								if (conto.ok()) break;
+							}
+							else
+								if (tok == "CA")
+								{
+									CHECK(_caus,"Causale documento non valida");
+									if (_caus->IVA2bill(codiva,conto)) break;
+								}
+						}
+					}
+
+					static int __searching = false;
+					
+					if (!conto.ok() && t == RIGA_SPESEDOC && !__searching)
+					{
+						const int rows = r.doc().physical_rows();
+						int row = -1;
+
+						for (int i = 1; row <0 && i <= rows; i++)
+						{
+							const char tipo = r.doc()[i].tipo().tipo();
+
+							if (tipo != RIGA_DESCRIZIONI &&	tipo != RIGA_SCONTI && tipo != RIGA_OMAGGI)
+								row = i;
+						}
+						if (row > 0)
+						{
+							__searching = true;
+							search_costo_ricavo(conto, r.doc()[row]);
+							__searching = false;
+						}
+					}
+				}
+			}
       break;  // case 'P','S'
     }
     case 'C':
@@ -3935,4 +3958,4 @@ bool TContabilizzazione::call_exe(const TDocumento& doc, const TMovimentoPN& mov
     ::remove(ininame);
   
   return ok;
-}
+}
\ No newline at end of file
diff --git a/ve/velib04d.cpp b/ve/velib04d.cpp
index 28e1ed61e..741ceebb9 100755
--- a/ve/velib04d.cpp
+++ b/ve/velib04d.cpp
@@ -254,6 +254,42 @@ TConsegna_mask::TConsegna_mask(int header_code, bool per_codice, bool ignora_des
 // TConsegna ordini
 ///////////////////////////////////////////////////////////
 
+bool TConsegna_ordini::calcola_ncolli_tara_pnetto(const TString& codart, const real& qta,
+                                                  real& ncolli, real& tara, real& pnetto) const
+{
+  const TRectype& articolo = cache().get(LF_ANAMAG, codart);
+  const real ppcollo = articolo.get_real(ANAMAG_PPCOLLO);
+  const bool ok = ppcollo > ZERO;
+  if (ok)
+  {
+    ncolli = qta / ppcollo;
+    ncolli.ceil(0);
+
+    tara = ncolli * articolo.get_real(ANAMAG_TARA);
+    pnetto = qta * articolo.get_real(ANAMAG_PESO);
+  }
+
+  return ok;
+}
+
+bool TConsegna_ordini::aggiorna_ncolli_tara_pnetto(TRiga_documento& r) const
+{
+  const TString& codart = r.get(RDOC_CODARTMAG);
+  TArticolo articolo(codart);
+  const real qta = articolo.convert_to_um(r.quantita(), NULL, r.get(RDOC_UMQTA));
+  real ncolli, tara, pnetto;
+
+  const bool ok = calcola_ncolli_tara_pnetto(codart, qta, ncolli, tara, pnetto);
+  if (ok)
+  {
+    r.put(RDOC_NCOLLI, ncolli);
+    r.put(RDOC_TARA, tara);
+    r.put(RDOC_PNETTO, pnetto);
+  }
+
+  return ok;
+}
+
 bool TConsegna_ordini::elabora(TLista_documenti& doc_in, TLista_documenti& doc_out,
                                const TDate& data_elab, bool interattivo)
 { 
@@ -364,13 +400,15 @@ bool TConsegna_ordini::elabora(TLista_documenti& doc_in, TLista_documenti& doc_o
           if (daeva > ZERO || row->get_char(S_RIGAEVASA-FIRST_FIELD) > ' ')
           {  
             const char* fqe = inrec.field_qtaevasa();
-            const real qtaevasa = inrec.get_real(fqe) + daeva;
-            inrec.put(fqe, qtaevasa);
+            // const real qtaevasa = inrec.get_real(fqe) + daeva;
+            // inrec.put(fqe, qtaevasa);
+            inrec.add(fqe, daeva);  // nuovo modo di incrementare
+
             inrec.put(RDOC_RIGAEVASA, row->get(S_RIGAEVASA - FIRST_FIELD));
           }
           if (articolo.not_empty())
           {                                           
-            const TString16 um(inrec.get(RDOC_UMQTA));
+            const TString4 um(inrec.get(RDOC_UMQTA));
             const real qta = art.convert_to_um(daeva,  params().get("UM"), um);
             params().set("QUANTITA", qta + params().get_real("QUANTITA"));
           }
@@ -385,10 +423,19 @@ bool TConsegna_ordini::elabora(TLista_documenti& doc_in, TLista_documenti& doc_o
                 continue;
               if (inrec.raggruppabile(outrec, campi_riga)) // Se esiste una riga compatibile ...
               {                                                     
-                const TString& qta_field = outrec.field_qta();
-                const real qta = outrec.get_real(qta_field) + daeva;
-                outrec.put(qta_field, qta);
-                outrec.dirty_fields();                 // Forza ricalcolo peso etc. 
+                if (!daeva.is_zero())
+                {
+                  const TString& qta_field = outrec.field_qta();
+                  outrec.add(qta_field, daeva); // nuovo modo di incrementare
+                
+                  real ncolli, tara, pnetto;
+                  calcola_ncolli_tara_pnetto(outrec.get(RDOC_CODARTMAG), daeva, ncolli, tara, pnetto);
+                  outrec.add(RDOC_NCOLLI, ncolli);
+                  outrec.add(RDOC_TARA, tara);
+                  outrec.add(RDOC_PNETTO, pnetto);
+                
+                  outrec.dirty_fields();                 // Forza ricalcolo formule 
+                }
                 elaborata = true;                      // Ricorda di averla gia' elaborata
                 break;
               }  
@@ -409,6 +456,13 @@ bool TConsegna_ordini::elabora(TLista_documenti& doc_in, TLista_documenti& doc_o
               if (q.is_zero()) 
                 outrec.put(RDOC_QTA, UNO);             // Pezza temporanea
             }
+            aggiorna_ncolli_tara_pnetto(outrec);
+            if (kill_descrizione_estesa())             // Cancello eventualmente la descrizione estesa
+            {
+              outrec.zero(RDOC_DESCLUNGA);
+              outrec.zero(RDOC_DESCEST);
+            }
+
             outrec.dirty_fields();                     // Forza ricalcolo peso etc. 
             outrec.zero(qtaevasa_field);               // Azzera quantita' evasa erroneamente copiata dall'ordine
             outrec.zero(RDOC_RIGAEVASA);               // Azzera flag di evasa erroneamente copiata dall'ordine
diff --git a/ve/velib04e.cpp b/ve/velib04e.cpp
index a719bacc5..21a69bb90 100755
--- a/ve/velib04e.cpp
+++ b/ve/velib04e.cpp
@@ -1,5 +1,6 @@
 #include <automask.h>
 #include <diction.h>
+#include <utility.h>
 
 #include "velib04.h"
 #include "velib04e.h"
@@ -23,15 +24,27 @@ static bool scan_rilprod(const TRelation& rel, void* pJolly)
   const TRectype& rec = rel.curr();
   TSheet_field& sheet = *(TSheet_field*)pJolly;
   TToken_string& row = sheet.row(-1);
-  row.add(rec.get(RDOC_CODART),   sheet.cid2index(S_CODART));
-  row.add(rec.get("PROG"),        sheet.cid2index(S_PROG));
-  row.add(rec.get("DATAPROD"),    sheet.cid2index(S_DATAPROD));
-  row.add(rec.get("ORAPROD"),     sheet.cid2index(S_ORAPROD));
-  row.add(rec.get("DATAFINE"),    sheet.cid2index(S_DATAFINE));
-  row.add(rec.get("ORAFINE"),     sheet.cid2index(S_ORAFINE));
+	TLocalisamfile righe(LF_RRILPROD);
+	const TString codart(rec.get(RDOC_CODART));
+	const int prog = rec.get_int("PROG");
+	const TDate data(rec.get("DATA"));
+
+	righe.put("CODART",   codart);
+  righe.put("DATA",     data);
+  righe.put("PROG",     prog);
+	righe.put("NRIGA",   999);
+
+  int err = righe.read(_isequal, _testandlock);
+	if (err == _iskeynotfound)
+		righe.prev();
+  row.add(codart,   sheet.cid2index(S_CODART));
+  row.add(format("%d", prog),     sheet.cid2index(S_PROG));
+  row.add(data.string(),          sheet.cid2index(S_DATA));
   row.add(rec.get(RDOC_IMPIANTO), sheet.cid2index(S_IMPIANTO));
   row.add(rec.get(RDOC_LINEA),    sheet.cid2index(S_LINEA));
-  row.add(rec.get(RDOC_QTA),      sheet.cid2index(S_QTA));
+	if (codart == righe.get("CODART"))
+		row.add(righe.get("DATAFINE"), sheet.cid2index(S_DATAPROD));
+	row.add(rec.get(RDOC_QTA),      sheet.cid2index(S_QTA));
   row.add(rec.get("CHIUSO"),      sheet.cid2index(S_CHIUSO));
 
   row.add(rec.get(RDOC_PROVV),    sheet.cid2index(S_PROVV));
@@ -39,13 +52,13 @@ static bool scan_rilprod(const TRelation& rel, void* pJolly)
   row.add(rec.get(RDOC_CODNUM),   sheet.cid2index(S_CODNUM));
   row.add(rec.get(RDOC_NDOC),     sheet.cid2index(S_NDOC));
   row.add(rec.get(RDOC_NRIGA),    sheet.cid2index(S_NRIGA));
-  return false;
+  return true;
 }
 
 void TConsuntivazione_mask::load_sheet()
 {
   TRelation rel(LF_RILPROD);
-  TCursor cur(&rel, "ANNOP=''", 5);
+  TCursor cur(&rel, "CODNUMP==\"\"");
 
   TSheet_field& sheet = sfield(F_SHEET);
   sheet.destroy();
@@ -60,7 +73,38 @@ bool TConsuntivazione_mask::on_field_event(TOperable_field& o, TField_event e, l
   {
   case F_SHEET:
     if (e == fe_init)
+		{
       load_sheet();
+      TSheet_field& s = sfield(F_SHEET);
+      FOR_EACH_SHEET_ROW(s, n, row)
+      {        
+        const real  r(row->get(s.cid2index(S_QTA)));
+
+        if (r <= ZERO)
+					s.disable_row(n);
+      }
+      s.force_update();
+		}
+    break;
+  case DLG_TUTTE:
+    if (e == fe_button)
+    {
+      TSheet_field& s = sfield(F_SHEET);
+      FOR_EACH_SHEET_ROW(s, n, row)
+      {        
+				const int pos = s.cid2index(S_SELECTED);
+        const TString16  v(row->get(pos));
+
+        if (s.row_enabled(n))
+				{
+					if (v.blank())
+	          row->add("X", pos);
+					else
+			      row->add(" ", pos);
+				}
+      }
+      s.force_update();
+    }
     break;
   default:
     break;
@@ -68,90 +112,158 @@ bool TConsuntivazione_mask::on_field_event(TOperable_field& o, TField_event e, l
   return true;
 }
 
+bool TConsuntivazione_produzione::ref2doc(char & provv, int & anno, TString8 & codnum, long & ndoc, int & nriga, const TString & codart)
+{
+	const TString8 ordprod(tipo_iniziale(0));
+	bool ok = true;
+
+	if (codnum != ordprod)
+	{
+
+		char p = provv;
+		int a = anno;
+		TString8 c(codnum);
+		long nd = ndoc;
+		int nr = nriga;
+		TLocalisamfile f(LF_RIGHEDOC);
+		TRectype & rec = f.curr();
+
+		rec.put(RDOC_DAPROVV, p);
+		rec.put(RDOC_DAANNO, a);
+		rec.put(RDOC_DACODNUM, c);
+		rec.put(RDOC_DANDOC, nd);
+		rec.put(RDOC_DAIDRIGA, nr);
+		
+		TRectype cmp(rec);
+
+		f.setkey(4);
+		ok = false;
+		for (int err = f.read(_isequal); !ok && rec == cmp && err == NOERR; f.next())
+		{
+			if (rec.get(RDOC_CODNUM) == ordprod)
+				if(rec.get(RDOC_CODARTMAG) == codart)
+				{
+					provv = rec.get_char(RDOC_PROVV);
+					anno = rec.get_int(RDOC_ANNO);
+					codnum = rec.get(RDOC_CODNUM);
+					ndoc = rec.get_long(RDOC_NDOC);
+					nriga = rec.get_int(RDOC_NRIGA);
+					ok = true;
+				}
+		}
+	}
+	return ok;
+}
+
 bool TConsuntivazione_produzione::elabora(TLista_documenti& doc_in, TLista_documenti& doc_out,
                                           const TDate& data_elab, bool interattivo)
 { 
   TConsuntivazione_mask msk;
   bool done = false;
-  while (msk.run() == K_ENTER)
+  if (msk.run() == K_ENTER)
   {
     TSheet_field& sheet = msk.sfield(F_SHEET);
     TLocalisamfile rilevazioni(LF_RILPROD);
     TRectype& ril = rilevazioni.curr();
 
-    TDocumento& outdoc = doc_out[0];
+		if (doc_out.items() == 0)
+		{
+			TDocumento d('D', data_elab.year(), codice_numerazione_finale(), 0L);
+			d.set_tipo(tipo_finale());
+			d.stato(stato_finale()[0]);
+			d.put(DOC_DATADOC, data_elab);
+			d.write();
+			TDocumento * d1 = new TDocumento(d.head());
+			doc_out.add(d1);
+		}
 
-    TDocumento ordine;
+    TDocumento& outdoc = doc_out[0];
+	  TDocumento ordine;
 
     FOR_EACH_SHEET_ROW(sheet, i, row) if (*row->get(0)=='X')  // Per ogni riga selezionata
     {
       const TString codart  = row->get(sheet.cid2index(S_CODART));
-      const TDate dataprod  = row->get(sheet.cid2index(S_DATAPROD));
+      const TDate data      = row->get(sheet.cid2index(S_DATA));
       const int prog        = row->get_int(sheet.cid2index(S_PROG));
       const real qta        = row->get(sheet.cid2index(S_QTA));
       bool chiuso           = row->get(sheet.cid2index(S_CHIUSO))[0] > ' ';
-      const char provv      = row->get(sheet.cid2index(S_PROVV))[0];
-      const int anno        = row->get_int(sheet.cid2index(S_ANNO));
-      const TString8 codnum = row->get(sheet.cid2index(S_CODNUM));
-      const long ndoc       = row->get_long(sheet.cid2index(S_NDOC));
-      const int nriga       = row->get_int(sheet.cid2index(S_NRIGA));
+      char provv      = row->get(sheet.cid2index(S_PROVV))[0];
+      int anno        = row->get_int(sheet.cid2index(S_ANNO));
+      TString8 codnum = row->get(sheet.cid2index(S_CODNUM));
+      long ndoc       = row->get_long(sheet.cid2index(S_NDOC));
+      int nriga       = row->get_int(sheet.cid2index(S_NRIGA));
 
-      int err = ordine.read(provv, anno, codnum, ndoc, _isequal, _testandlock);
-      if (err == NOERR)
-      {
-        if (nriga > 0 && nriga <= ordine.rows())
-        {
-          TRiga_documento& riga_ordine = ordine[nriga];
-          const TString& qta_fld = riga_ordine.field_qta();
-          const TString& qte_fld = riga_ordine.field_qtaevasa();
+      int err;
+			
+			if (ref2doc(provv, anno, codnum, ndoc, nriga, codart))
+			{
+				int err = ordine.read(provv, anno, codnum, ndoc, _isequal, _testandlock);
+				if (err == NOERR)
+				{
+					if (nriga > 0 && nriga <= ordine.rows())
+					{
+						TRiga_documento& riga_ordine = ordine[nriga];
+						const TString& qta_fld = riga_ordine.field_qta();
+						const TString& qte_fld = riga_ordine.field_qtaevasa();
 
-          const real qta_evasa = riga_ordine.qtaevasa() + qta;      
-          riga_ordine.put(qte_fld, qta_evasa);
-          if (chiuso || riga_ordine.qtaresidua().is_zero())
-          {
-            riga_ordine.put(RDOC_RIGAEVASA, 'X');
-            chiuso = true;
-          }
+						const real qta_evasa = riga_ordine.qtaevasa() + qta;      
+						riga_ordine.put(qte_fld, qta_evasa);
+						if (chiuso || riga_ordine.qtaresidua().is_zero())
+						{
+							riga_ordine.put(RDOC_RIGAEVASA, 'X');
+							chiuso = true;
+						}
 
-          const TString4 tiporiga = riga_ordine.get(RDOC_TIPORIGA);
-          TRiga_documento& outrec = outdoc.new_row(tiporiga);
-          TDocumento::copy_data(outrec, riga_ordine);
-          outrec.put(qta_fld, qta);
-          if (qta_fld != RDOC_QTA) 
-          {
-            const real q = riga_ordine.get_real(RDOC_QTA);
-            if (q.is_zero()) 
-              outrec.put(RDOC_QTA, UNO);             // Pezza temporanea
-          }
-          outrec.dirty_fields();                     // Forza ricalcolo peso etc. 
-          outrec.put(RDOC_DATACONS, dataprod);       // Setta la data di consegna con la data di produzione
-          outrec.zero(qte_fld);                      // Azzera quantita' evasa erroneamente copiata dall'ordine
-          outrec.zero(RDOC_RIGAEVASA);               // Azzera flag di evasa erroneamente copiata dall'ordine
-          outrec.set_original_rdoc_key(riga_ordine);
-        }
-        else
-        {
-          err = _iskeynotfound;
-        }
-        err = ordine.rewrite();  // Unlocca
-      }
-      if (err != NOERR)
-      {
-        const char* msg = TR("Impossibile aggiornare il documento");
-        error_box("%s %d %s %ld", msg, anno, (const char*)codnum, ndoc);
-        break;
+						const TString4 tiporiga = riga_ordine.get(RDOC_TIPORIGA);
+						TRiga_documento& outrec = outdoc.new_row(tiporiga);
+						TDocumento::copy_data(outrec, riga_ordine);
+						outrec.put(qta_fld, qta);
+						if (qta_fld != RDOC_QTA) 
+						{
+							const real q = riga_ordine.get_real(RDOC_QTA);
+							if (q.is_zero()) 
+								outrec.put(RDOC_QTA, UNO);             // Pezza temporanea
+						}
+						if (kill_descrizione_estesa())             // Cancello eventualmente la descrizione estesa
+						{
+							outrec.zero(RDOC_DESCLUNGA);
+							outrec.zero(RDOC_DESCEST);
+						}
+						outrec.dirty_fields();                     // Forza ricalcolo peso etc. 
+						outrec.put(RDOC_DATACONS, data);           // Setta la data di consegna con la data di produzione
+						outrec.zero(qte_fld);                      // Azzera quantita' evasa erroneamente copiata dall'ordine
+						outrec.zero(RDOC_RIGAEVASA);               // Azzera flag di evasa erroneamente copiata dall'ordine
+						outrec.set_original_rdoc_key(riga_ordine);
+					}
+					else
+					{
+		        const char* msg = TR("Impossibile aggiornare il documento");
+				    error_box("%s %d %s %ld", msg, anno, (const char*)codnum, ndoc);
+					}
+					if (ordine.is_evaso())
+						ordine.stato(stato_finale_doc_iniziale()[0]);
+					err = ordine.rewrite();  // Unlocca
+		      if (err != NOERR)
+				  {
+		        const char* msg = TR("Impossibile aggiornare il documento");
+				    error_box("%s %d %s %ld", msg, anno, (const char*)codnum, ndoc);
+					}
+				}
+				else
+				{
+		      const char* msg = TR("Impossibile trovare l'ordine di produzione");
+				  error_box("%s %d %s %ld", msg, anno, (const char*)codnum, ndoc);
+				}
       }
 
       ril.put("CODART",   codart);
-      ril.put("DATAPROD", dataprod);
+      ril.put("DATA",     data);
       ril.put("PROG",     prog);
       err = rilevazioni.read(_isequal, _testandlock);
       if (err == NOERR)
       {
-        ril.put("QTA",      qta);
-        ril.put("CHIUSO",   chiuso);
-        ril.put("IMPIANTO", row->get(sheet.cid2index(S_IMPIANTO)));
-        ril.put("LINEA",    row->get(sheet.cid2index(S_LINEA)));
+				if (chiuso)
+	        ril.put("CHIUSO", chiuso);
         ril.put("PROVVP",   outdoc.get(DOC_PROVV));
         ril.put("ANNOP",    outdoc.get(DOC_ANNO));
         ril.put("CODNUMP",  outdoc.get(DOC_CODNUM));
@@ -162,7 +274,7 @@ bool TConsuntivazione_produzione::elabora(TLista_documenti& doc_in, TLista_docum
       if (err != NOERR)
       {
         const char* msg = TR("Impossibile aggiornare la riga di rilevazione");
-        error_box("%s %s %s %d", msg, (const char*)codart, (const char*)dataprod.string(), prog);
+        error_box("%s %s %s %d", msg, (const char*)codart, (const char*)data.string(), prog);
         break;
       }
       else
diff --git a/ve/velib04e.h b/ve/velib04e.h
index 6325b340e..0db4992e8 100755
--- a/ve/velib04e.h
+++ b/ve/velib04e.h
@@ -4,19 +4,19 @@
 #define S_CODART         102
 #define S_DESCR_ART      152
 #define S_PROG           103
-#define S_DATAPROD       104
-#define S_ORAPROD        105
-#define S_DATAFINE       106
-#define S_ORAFINE        107
-#define S_IMPIANTO       108
+#define S_DATA           104
+#define S_IMPIANTO       105
 #define S_DESCR_IMPIANTO 158
-#define S_LINEA          109
+#define S_LINEA          106
 #define S_DESCR_LINEA    159
-#define S_QTA            110
-#define S_CHIUSO         111
+#define S_DATAPROD       107
+#define S_QTA            108
+#define S_CHIUSO         109
 
-#define S_PROVV          112
-#define S_ANNO           113
-#define S_CODNUM         114
-#define S_NDOC           115
-#define S_NRIGA          116
+#define S_PROVV          110
+#define S_ANNO           111
+#define S_CODNUM         112
+#define S_NDOC           113
+#define S_NRIGA          114
+
+#define DLG_TUTTE        201
\ No newline at end of file
diff --git a/ve/velib04e.uml b/ve/velib04e.uml
index 804c2b0d8..ed8f04d99 100755
--- a/ve/velib04e.uml
+++ b/ve/velib04e.uml
@@ -4,13 +4,18 @@ TOOLBAR "Toolbar" 0 -2 0 2
 
 BUTTON DLG_OK 10 2
 BEGIN
-  PROMPT -12 -11 "E~labora"
+  PROMPT -13 -11 "E~labora"
   PICTURE BMP_ELABORA
 END
 
+BUTTON DLG_TUTTE 10 2
+BEGIN
+  PROMPT -23 -11 "~Tutte"
+END
+
 BUTTON DLG_QUIT 10 2
 BEGIN
-  PROMPT -22 -11 ""
+  PROMPT -33 -11 ""
 END
 
 ENDPAGE
@@ -23,12 +28,10 @@ BEGIN
   ITEM "@1"
   ITEM "Articolo@20"
   ITEM "Progr."
-  ITEM "Data Prod.@10"
-  ITEM "Ora@6"
-  ITEM "Data Fine@10"
-  ITEM "Ora@6"
+  ITEM "Data Ord.@10"
   ITEM "Impianto"
   ITEM "Linea"
+	ITEM "Data Prod."
   ITEM "Quantita'@15"
   ITEM "Chiuso"
   ITEM "Provv.@5"
@@ -76,31 +79,12 @@ BEGIN
   FLAGS "DU"
 END
 
-DATE S_DATAPROD 
+DATE S_DATA
 BEGIN
-  PROMPT 32 2 "Data produzione "
+  PROMPT 32 2 "Data ordine     "
   FLAGS "D"
 END
 
-NUMBER S_ORAPROD 6
-BEGIN
-  PROMPT 64 2 "Ora "
-  FLAGS "DUZ"
-END
-
-
-DATE S_DATAFINE
-BEGIN
-  PROMPT 32 3 "Fine produzione "
-  FLAGS "D"
-END
-
-NUMBER S_ORAFINE 6
-BEGIN
-  PROMPT 64 3 "Ora "
-  FLAGS "DUZ"
-END
-
 STRINGA S_IMPIANTO 5
 BEGIN
   PROMPT 2 4 "Impianto "
@@ -111,7 +95,7 @@ BEGIN
   OUTPUT S_IMPIANTO CODTAB
   OUTPUT S_DESCR_IMPIANTO S0
   CHECKTYPE NORMAL
-  FLAGS "U"
+  FLAGS "UD"
 END
 
 STRINGA S_DESCR_IMPIANTO 50
@@ -122,6 +106,7 @@ BEGIN
   DISPLAY "Descrizione@50" S0
   DISPLAY "Codice" CODTAB
   COPY OUTPUT S_IMPIANTO
+	FLAGS "D"
   CHECKTYPE NORMAL
 END
 
@@ -136,7 +121,7 @@ BEGIN
   OUTPUT S_LINEA CODTAB
   OUTPUT S_DESCR_LINEA S0
   CHECKTYPE NORMAL
-  FLAGS "U"
+  FLAGS "UD"
 END
 
 STRINGA S_DESCR_LINEA 50
@@ -147,20 +132,27 @@ BEGIN
   DISPLAY "Descrizione@50" S0
   DISPLAY "Codice" CODTAB
   COPY OUTPUT S_LINEA
+	FLAGS "D"
   CHECKTYPE NORMAL
 END
 
+DATE S_DATAPROD
+BEGIN
+  PROMPT 32 2 "Data produzione "
+  FLAGS "D"
+END
 
 NUMBER S_QTA 15 5
 BEGIN
   PROMPT 2 6 "Quantita'"
-  FLAGS "U"
+  FLAGS "D"
   CHECKTYPE REQUIRED
 END
 
 BOOLEAN S_CHIUSO
 BEGIN
   PROMPT 42 6 "Chiuso"
+	FLAGS "D"
 END
 
 GROUPBOX DLG_NULL 78 4
diff --git a/ve/velib06.cpp b/ve/velib06.cpp
index 84892006f..5c29897f7 100755
--- a/ve/velib06.cpp
+++ b/ve/velib06.cpp
@@ -1739,8 +1739,11 @@ void TDocument_tree::append_custom_fields(const TTipo_documento& tipo, const TRe
       str << format.sub(ch+1, ap);
       ch = format.find('}', ap);
       const TString16 field = format.sub(ap+1, ch);
-      format_field(rec, field, tmp);
-      str << tmp;
+      if (!field.blank())
+      {
+        format_field(rec, field, tmp);
+        str << tmp;
+      }
     }
     str << format.mid(ch+1);
   }
diff --git a/ve/vetbdip.h b/ve/vetbdip.h
new file mode 100755
index 000000000..4d8da6363
--- /dev/null
+++ b/ve/vetbdip.h
@@ -0,0 +1,45 @@
+#define F_CODICE        101
+#define F_COGNOME       102
+#define F_NOME          103
+#define F_COLLAB        104
+#define F_CODFORN       105
+#define F_CODFIS        106
+#define F_ADDRESS       107
+#define F_CIVICO        108
+#define F_STATO         109
+#define F_DESTATO       110
+#define F_COMUNE        111
+#define F_DENCOM        112
+#define F_LOCALITA      113
+#define F_CAP           114
+#define F_PROV          115
+#define F_MRP_ATTIVO    116
+#define F_IMPIANTO      117
+#define F_LINEA         118
+#define F_CODIVA        119
+#define F_DESIVA        120
+#define F_CODVAL        121
+#define F_DESVAL        122
+
+#define F_CAMPI         123
+#define F_PREZZO        124
+#define F_QTA           125
+#define F_UM            126
+
+#define F_GRUPPOV       129
+#define F_CONTOV        130
+#define F_SOTTOV        131
+#define F_DESCRCONTOV   132
+#define F_GRUPPOA       133
+#define F_CONTOA        134
+#define F_SOTTOA        135
+#define F_DESCRCONTOA   136
+
+#define F_GRUPPOPCIA     140
+#define F_CONTOPCIA      141
+#define F_SOTTOPCIA      142
+#define F_DESCRCONTOPCIA 143
+#define F_GRUPPOPCIV     144
+#define F_CONTOPCIV      145
+#define F_SOTTOPCIV      146
+#define F_DESCRCONTOPCIV 147
diff --git a/ve/vetbdip.uml b/ve/vetbdip.uml
new file mode 100755
index 000000000..735557312
--- /dev/null
+++ b/ve/vetbdip.uml
@@ -0,0 +1,574 @@
+#include "vetbdip.h"
+
+TOOLBAR "" 0 20 60 2
+#include <toolbar.h>
+ENDPAGE
+
+PAGE "Tabella dipendenti" 11 60 14
+
+GROUPBOX DLG_NULL 75 5
+BEGIN
+ PROMPT 1 0 ""
+ FLAGS "R"
+END
+
+STRING F_CODICE 16
+BEGIN
+  PROMPT 2 1 "Codice  "
+  FIELD CODTAB
+  KEY 1
+  USE DIP
+  FLAGS "U"
+  INPUT CODTAB  F_CODICE
+  DISPLAY "Codice@16" CODTAB
+  DISPLAY "Cognome@40" S0[1,40]
+  DISPLAY "Nome@30" S0[41,70]
+  OUTPUT F_CODICE CODTAB
+  OUTPUT F_COGNOME S0[1,40]
+  OUTPUT F_NOME S0[41,70]
+  CHECKTYPE REQUIRED
+  MESSAGE COPY,11@
+END
+
+STRING F_COGNOME 40
+BEGIN
+  PROMPT 2 2 "Cognome "
+  FIELD S0[1,40]
+  KEY 2
+  USE DIP KEY 2
+  INPUT S0[1,40] F_COGNOME
+  DISPLAY "Cognome@40" S0[1,40]
+  DISPLAY "Nome@30" S0[41,70]
+  DISPLAY "Codice@16" CODTAB
+  COPY OUTPUT F_CODICE
+  CHECKTYPE REQUIRED
+  MESSAGE COPY,12@
+END
+
+STRING F_NOME 30
+BEGIN
+  PROMPT 2 3 "Nome    "
+  FIELD S0[41,70]
+  KEY 2
+  USE DIP KEY 2
+  INPUT S0[41,70] F_NOME
+  DISPLAY "Nome@30" S0[41,70]
+  DISPLAY "Cognome@40" S0[1,40]
+  DISPLAY "Codice@16" CODTAB
+  COPY OUTPUT F_CODICE
+  CHECKTYPE REQUIRED
+  MESSAGE COPY,13@
+END
+
+BOOLEAN F_COLLAB
+BEGIN
+  PROMPT 2 5 "Collaboratore"
+  FIELD B0
+  MESSAGE FALSE CLEAR,F_CODFORN|ENABLE,10@
+  MESSAGE TRUE ENABLE,F_CODFORN|CLEAR,10@
+END
+
+NUMBER F_CODFORN 6
+BEGIN
+  PROMPT 2 6 "Codice fornitore "
+  FIELD I6
+  USE LF_CLIFO
+  INPUT TIPOCF "F"
+  INPUT CODCF F_CODFORN
+  DISPLAY "Codice" CODCF
+  DISPLAY "Ragione Sociale@50" RAGSOC
+  OUTPUT F_CODFORN CODCF
+  OUTPUT F_ADDRESS INDCF
+  OUTPUT F_CIVICO CIVCF
+  OUTPUT F_STATO STATOCF 
+  OUTPUT F_COMUNE COMCF
+  OUTPUT F_LOCALITA LOCALITACF
+  OUTPUT F_CAP CAPCF
+  OUTPUT F_CODFIS COFI
+  OUTPUT F_CODIVA PAIVA
+END
+
+STRING F_CODFIS 16
+BEGIN
+  PROMPT 2 7 "Codice fiscale   "
+  FIELD S3[5,21]
+  FLAGS "U"
+  GROUP 10
+END
+
+GROUPBOX DLG_NULL 76 6
+BEGIN
+  PROMPT 1 8 "@bRecapito"
+END
+
+STRING F_ADDRESS 35
+BEGIN
+  PROMPT 2 9 "Indirizzo "
+  FIELD S1[1,35]
+  GROUP 10
+END
+
+STRING F_CIVICO 5
+BEGIN
+  PROMPT 65 9 "N. "
+  FIELD S3[26,35]
+  GROUP 10
+END
+
+NUMBER F_STATO 3
+BEGIN
+  PROMPT 2 10 "Comune: Stato "
+  FIELD I7
+  FLAGS "Z"
+  USE %STA
+  INPUT CODTAB F_STATO
+  DISPLAY "Codice" CODTAB
+  DISPLAY "Stato@50" S0
+  OUTPUT F_STATO CODTAB
+  OUTPUT F_DESTATO S0
+  CHECKTYPE NORMAL
+  GROUP 10
+END
+
+STRING F_DESTATO 50
+BEGIN
+  PROMPT 23 10 ""
+  USE %STA KEY 2
+  INPUT S0 F_DESTATO
+  DISPLAY "Stato@60" S0
+  DISPLAY "Codice" CODTAB
+  COPY OUTPUT F_STATO
+  GROUP 10
+END
+
+STRING F_COMUNE 4
+BEGIN
+  PROMPT 8 11 ":Codice "
+  FIELD S3[22,25]
+  FLAGS "U"
+  USE LF_COMUNI
+  INPUT STATO F_STATO SELECT
+  INPUT COM F_COMUNE
+  DISPLAY "Stato" STATO
+  DISPLAY "Codice" COM
+  DISPLAY "Comune@50" DENCOM
+  OUTPUT F_STATO STATO
+  OUTPUT F_COMUNE COM
+  OUTPUT F_CAP CAPCOM
+  OUTPUT F_DENCOM DENCOM
+  OUTPUT F_PROV PROVCOM
+  CHECKTYPE NORMAL
+  ADD RUN ba4 -0
+  GROUP 10
+END
+
+STRING F_DENCOM 50
+BEGIN
+  PROMPT 23 11 ""
+  USE LF_COMUNI KEY 2
+  INPUT DENCOM F_DENCOM
+  DISPLAY "Comune@50" DENCOM
+  DISPLAY "Stato" STATO
+  DISPLAY "Codice" COM
+  COPY OUTPUT F_COMUNE
+  ADD RUN ba4 -0
+  GROUP 10
+END
+
+STRING F_LOCALITA 35
+BEGIN
+  PROMPT 2 12 "Localita'     "
+  FIELD S1[36,70]
+  GROUP 10
+END
+
+STRING F_CAP 5
+BEGIN
+  PROMPT 53 12 "CAP "
+  FIELD I8
+  GROUP 10
+END
+
+STRING F_PROV 5
+BEGIN
+  PROMPT 64 12 "Prov"
+  FLAGS "D"
+  GROUP 10
+END
+
+BOOLEAN F_MRP_ATTIVO
+BEGIN
+  PROMPT 1 14 "@bCollegamento M.R.P.:"
+  MESSAGE FALSE CLEAR,9@
+  MESSAGE TRUE ENABLE,9@
+//  FLAGS "H"
+END
+
+STRING F_IMPIANTO 5
+BEGIN
+  PROMPT 23 14 "Impianto "
+  FIELD S8
+  USE IMP
+  INPUT CODTAB F_IMPIANTO
+  DISPLAY "Codice" CODTAB
+  DISPLAY "Descrizione@50" S0
+  OUTPUT F_IMPIANTO CODTAB
+  GROUP 9
+END
+
+STRING F_LINEA 5
+BEGIN
+  PROMPT 45 14 "Linea "
+  FIELD S9
+  USE LNP
+  INPUT CODTAB F_LINEA
+  DISPLAY "Codice" CODTAB
+  DISPLAY "Descrizione@50" S0
+  OUTPUT F_LINEA CODTAB
+  GROUP 9
+END
+
+ENDPAGE
+
+PAGE "Pagina 2" 11 60 14
+
+GROUPBOX DLG_NULL 75 5
+BEGIN
+ PROMPT 1 0 ""
+ FLAGS "R"
+END
+
+STRING DLG_NULL 16
+BEGIN
+  PROMPT 2 1 "Codice  "
+  FLAGS "UD"
+  GROUP 11
+END
+
+STRING DLG_NULL 40
+BEGIN
+  PROMPT 2 2 "Cognome "
+  FLAGS "D"
+  GROUP 12
+END
+
+STRING DLG_NULL 30
+BEGIN
+  PROMPT 2 3 "Nome    "
+  FLAGS "D"
+  GROUP 13
+END
+
+STRING F_CODIVA 4
+BEGIN
+  PROMPT 2 7 "Codice IVA     "
+  FIELD S3[1,4]
+  FLAGS "U"
+  USE %IVA
+  INPUT CODTAB  F_CODIVA
+  DISPLAY "Codice " CODTAB
+  DISPLAY "Descrizione@50" S0
+  OUTPUT F_CODIVA CODTAB
+  OUTPUT F_DESIVA S0
+  CHECKTYPE NORMAL
+END
+
+
+STRING F_DESIVA 50
+BEGIN
+  PROMPT 25 7 ""
+  USE %IVA KEY 2
+  INPUT S0  F_DESIVA
+  DISPLAY "Descrizione@50" S0
+  DISPLAY "Codice " CODTAB
+  COPY OUTPUT F_CODIVA
+  CHECKTYPE NORMAL
+END
+
+STRING F_CODVAL 4
+BEGIN
+  PROMPT 2 8 "Codice valuta  "
+  FIELD S4
+  FLAGS "U"
+  USE %VAL
+  INPUT CODTAB  F_CODVAL
+  DISPLAY "Codice" CODTAB
+  DISPLAY "Descrizione@50" S0
+  OUTPUT F_CODVAL CODTAB
+  OUTPUT F_DESVAL S0
+  CHECKTYPE NORMAL
+END
+
+STRING F_DESVAL 50
+BEGIN
+  PROMPT 25 8 ""
+  USE %VAL KEY 2
+  INPUT S0  F_DESVAL
+  DISPLAY "Descrizione@50" S0
+  DISPLAY "Codice" CODTAB
+  COPY OUTPUT F_CODVAL
+  CHECKTYPE NORMAL
+END
+
+LISTBOX F_CAMPI 15
+BEGIN
+  PROMPT 2 9 "Campo default  "
+  FIELD S6
+  ITEM "Q|Qta prezzo "
+  MESSAGE SHOW,1@|ENABLE,2@
+  FLAGS "D"
+END
+
+CURRENCY F_PREZZO 15
+BEGIN
+  PROMPT 2 10 "Prezzo         "
+  FIELD R0          
+  FLAGS "U"
+  GROUP 1
+END
+
+NUMBER F_QTA 13 5
+BEGIN
+  PROMPT 35 10 "Quantita' "
+  FIELD R1
+  GROUP 1 2
+END
+
+STRING F_UM 2
+BEGIN
+  PROMPT 63 10 "U.M.   "
+  FIELD S7
+  FLAGS "U"
+  USE %UMS
+  INPUT CODTAB F_UM
+  DISPLAY "U.M." CODTAB
+  DISPLAY "Descrizione@50" S0
+  OUTPUT F_UM CODTAB
+  CHECKTYPE NORMAL
+  GROUP 1
+END
+
+NUMBER F_GRUPPOV 3
+BEGIN
+  PROMPT 2 11 "Conto vendita  "
+  FIELD I0
+  CHECKTYPE NORMAL
+ END
+
+NUMBER F_CONTOV 3
+BEGIN
+  PROMPT 22 11 ""
+  FIELD I1
+  USE LF_PCON SELECT (CONTO!="") && (SOTTOCONTO=="")
+  INPUT GRUPPO      F_GRUPPOV
+  INPUT CONTO       F_CONTOV
+  DISPLAY "Gruppo" GRUPPO
+  DISPLAY "Conto" CONTO
+  DISPLAY "Descrizione@50" DESCR
+  OUTPUT F_GRUPPOV  GRUPPO
+  OUTPUT F_CONTOV  CONTO
+  CHECKTYPE NORMAL
+  ADD RUN CG0 -0
+  WARNING "Il conto deve essere un ricavo"
+ END
+
+NUMBER F_SOTTOV 6
+BEGIN
+  PROMPT 30 11 ""
+  FIELD I2
+  USE LF_PCON SELECT SOTTOCONTO!=""
+  JOIN LF_PCON ALIAS 500 INTO GRUPPO==GRUPPO CONTO==CONTO
+  INPUT GRUPPO      F_GRUPPOV
+  INPUT CONTO       F_CONTOV
+  INPUT SOTTOCONTO  F_SOTTOV
+  DISPLAY "Gruppo" GRUPPO
+  DISPLAY "Conto" CONTO
+  DISPLAY "Sottoconto" SOTTOCONTO
+  DISPLAY "Descrizione@50" DESCR
+  OUTPUT F_GRUPPOV  GRUPPO
+  OUTPUT F_CONTOV  CONTO
+  OUTPUT F_SOTTOV  SOTTOCONTO
+  OUTPUT F_DESCRCONTOV  DESCR
+  CHECKTYPE NORMAL
+  WARNING "Sottoconto errato"
+  ADD RUN CG0 -0
+END
+
+STRING F_DESCRCONTOV 50
+BEGIN
+  PROMPT 17 12 ""
+  FLAG "U"
+  USE LF_PCON KEY 2 SELECT (SOTTOCONTO!="")
+  JOIN LF_PCON ALIAS 500 INTO GRUPPO==GRUPPO CONTO==CONTO
+  INPUT DESCR F_DESCRCONTOV
+  DISPLAY "Descrizione@50" DESCR
+  DISPLAY "Gruppo" GRUPPO
+  DISPLAY "Conto"  CONTO
+  DISPLAY "Sottoconto" SOTTOCONTO
+  COPY OUTPUT F_SOTTOV
+  CHECKTYPE NORMAL
+  WARNING "Il conto deve essere un ricavo"
+  ADD RUN CG0 -0
+END
+
+NUMBER F_GRUPPOA 3
+BEGIN
+  PROMPT 2 13 "Conto acquisti "
+  FIELD I3
+  CHECKTYPE NORMAL
+ END
+
+NUMBER F_CONTOA 3
+BEGIN
+  PROMPT 22 13 ""
+  FIELD I4
+  COPY USE F_CONTOV
+  INPUT GRUPPO      F_GRUPPOA
+  INPUT CONTO       F_CONTOA
+  DISPLAY "Gruppo" GRUPPO
+  DISPLAY "Conto" CONTO
+  DISPLAY "Descrizione@50" DESCR
+  OUTPUT F_GRUPPOA  GRUPPO
+  OUTPUT F_CONTOA  CONTO
+  CHECKTYPE NORMAL
+  WARNING "Il conto deve essere un costo"
+  ADD RUN CG0 -0
+ END
+
+NUMBER F_SOTTOA 6
+BEGIN
+  PROMPT 30 13 ""
+  FIELD I5
+  COPY USE F_SOTTOV
+  INPUT GRUPPO      F_GRUPPOA
+  INPUT CONTO       F_CONTOA
+  INPUT SOTTOCONTO  F_SOTTOA
+  COPY DISPLAY F_SOTTOV
+  OUTPUT F_GRUPPOA  GRUPPO
+  OUTPUT F_CONTOA  CONTO
+  OUTPUT F_SOTTOA  SOTTOCONTO
+  OUTPUT F_DESCRCONTOA  DESCR
+  CHECKTYPE NORMAL
+  WARNING "Sottoconto errato"
+  ADD RUN CG0 -0
+END
+
+STRING F_DESCRCONTOA 50
+BEGIN
+  PROMPT 17 14 ""
+  FLAG "U"
+  COPY USE F_DESCRCONTOV
+  INPUT DESCR F_DESCRCONTOA
+  COPY DISPLAY F_DESCRCONTOV
+  COPY OUTPUT F_SOTTOA
+  CHECKTYPE NORMAL
+  WARNING "Il conto deve essere un ricavo"
+  ADD RUN CG0 -0
+END
+
+STRING F_GRUPPOPCIA 3
+BEGIN
+  PROMPT 2 15 "Conto industr. "
+  FLAGS "Z"
+  FIELD S2[21,23]
+  CHECKTYPE NORMAL
+ END
+
+STRING F_CONTOPCIA 3
+BEGIN
+  PROMPT 22 15 ""
+  FLAGS "Z"
+  FIELD S2[24,26]
+END
+
+STRING F_SOTTOPCIA 6
+BEGIN
+  PROMPT 30 15 ""
+  FLAGS "Z"
+  FIELD S2[27,32]
+  USE PCI SELECT CODTAB[7,12]!=""
+  INPUT CODTAB[1,3] F_GRUPPOPCIA
+  INPUT CODTAB[4,6] F_CONTOPCIA
+  INPUT CODTAB[7,12] F_SOTTOPCIA
+  DISPLAY "Gruppo" CODTAB[1,3]
+  DISPLAY "Conto" CODTAB[4,6]
+  DISPLAY "Sottoconto" CODTAB[7,12]
+  DISPLAY "Descrizione@50" S0
+  OUTPUT F_GRUPPOPCIA CODTAB[1,3]
+  OUTPUT F_CONTOPCIA  CODTAB[4,6]
+  OUTPUT F_SOTTOPCIA  CODTAB[7,12]
+  OUTPUT F_DESCRCONTOPCIA S0
+  CHECKTYPE NORMAL
+  ADD RUN BA3 -0 PCI
+END
+
+STRING F_DESCRCONTOPCIA 50
+BEGIN
+  PROMPT 2 16 "acquisti       "
+  FLAG "U"
+  USE PCI KEY 2 SELECT (CODTAB[7,12]!="")
+  INPUT S0 F_DESCRCONTOPCIA
+  DISPLAY "Descrizione@50" S0
+  DISPLAY "Gruppo" CODTAB[1,3]
+  DISPLAY "Conto"  CODTAB[4,6]
+  DISPLAY "Sottoconto" CODTAB[7,12]
+  COPY OUTPUT F_SOTTOPCIA
+  CHECKTYPE NORMAL
+  ADD RUN BA0 -3 PCI
+END
+
+STRING F_GRUPPOPCIV 3
+BEGIN
+  PROMPT 2 17 "Conto industr. "
+  FLAGS "Z"
+  FIELD S2[1,3]
+  CHECKTYPE NORMAL
+END
+
+STRING F_CONTOPCIV 3
+BEGIN
+  PROMPT 22 17 ""
+  FLAGS "Z"
+  FIELD S2[4,6]
+END
+
+STRING F_SOTTOPCIV 6
+BEGIN
+  PROMPT 30 17 ""
+  FLAGS "Z"
+  FIELD S2[7,12]
+  USE PCI SELECT CODTAB[7,12]!=""
+  INPUT CODTAB[1,3] F_GRUPPOPCIV
+  INPUT CODTAB[4,6] F_CONTOPCIV
+  INPUT CODTAB[7,12] F_SOTTOPCIV
+  DISPLAY "Gruppo" CODTAB[1,3]
+  DISPLAY "Conto" CODTAB[4,6]
+  DISPLAY "Sottoconto" CODTAB[7,12]
+  DISPLAY "Descrizione@50" S0
+  OUTPUT F_GRUPPOPCIV CODTAB[1,3]
+  OUTPUT F_CONTOPCIV  CODTAB[4,6]
+  OUTPUT F_SOTTOPCIV  CODTAB[7,12]
+  OUTPUT F_DESCRCONTOPCIV S0
+  CHECKTYPE NORMAL
+  ADD RUN BA3 -0 PCI
+END
+
+STRING F_DESCRCONTOPCIV 50
+BEGIN
+  PROMPT 2 18 "vendita        "
+  FLAG "U"
+  USE PCI KEY 2 SELECT (CODTAB[7,12]!="")
+  INPUT S0 F_DESCRCONTOPCIV
+  DISPLAY "Descrizione@50" S0
+  DISPLAY "Gruppo" CODTAB[1,3]
+  DISPLAY "Conto"  CODTAB[4,6]
+  DISPLAY "Sottoconto" CODTAB[7,12]
+  COPY OUTPUT F_SOTTOPCIV
+  CHECKTYPE NORMAL
+  ADD RUN BA0 -3 PCI
+END
+
+
+ENDPAGE
+
+ENDMASK
diff --git a/xi/xi.h b/xi/xi.h
index 0737aa394..e5462cb40 100755
--- a/xi/xi.h
+++ b/xi/xi.h
@@ -104,6 +104,7 @@ typedef long STX;
 #define XI_ATR_SELECTABLE     0x4000L
 #define XI_ATR_COL_SELECTABLE 0x8000L
 #define XI_ATR_HCENTER        0x10000L
+#define XI_AGA_ATR_AUTOEND    0x20000L
 
 #define XI_MAX_EVENT      100
 #define XI_NULL_OBJ       (( XI_OBJ* ) NULL )
diff --git a/xi/xistx.c b/xi/xistx.c
index 39254d5bd..842036d41 100755
--- a/xi/xistx.c
+++ b/xi/xistx.c
@@ -592,7 +592,13 @@ stx_start_edit( STX stx )
       if ( stxp->attrib & XI_ATR_AUTOSELECT )
         xi_text_selection_set( stxp->xi_text, 0, SHRT_MAX );
       else
-        xi_text_selection_set( stxp->xi_text, 0, 0 );
+	      if ( stxp->attrib & XI_AGA_ATR_AUTOEND )
+				{
+					int len = strlen(stxp->xi_text->string);
+		      xi_text_selection_set( stxp->xi_text, len, len );
+				}
+				else
+		      xi_text_selection_set( stxp->xi_text, 0, 0 );
     }
   }
 }
diff --git a/xvaga/oswin32.cpp b/xvaga/oswin32.cpp
index 7ffa55905..bca0d834b 100755
--- a/xvaga/oswin32.cpp
+++ b/xvaga/oswin32.cpp
@@ -353,14 +353,12 @@ bool OsWin32_DrawBitmap(HBITMAP hBMP, wxDC& dc, const wxRect& dst, const wxRect&
   {
     HDC hDC = (HDC)dc.GetHDC();
 	  const int nTechno = ::GetDeviceCaps(hDC, TECHNOLOGY);
-    const int nDepth = ::GetDeviceCaps(hDC, BITSPIXEL);
 
     HDC hMemDC = NULL;
-    
-    if (nDepth == 1 && IsWin95())
-      hMemDC = ::CreateCompatibleDC(NULL);  // Per Win95 e Win98 devo fare cosi' ... almeno per ora
+    if (OsWin32_IsWindowsServer())
+      hMemDC = ::CreateCompatibleDC(hDC);   // Per Terminal Server devo fare cosi'
     else
-      hMemDC = ::CreateCompatibleDC(hDC);
+      hMemDC = ::CreateCompatibleDC(NULL);  // Per gli altri sistemi devo fare cosa'
     
     BITMAP bmp; ::GetObject(hBMP, sizeof(bmp), &bmp);
 	
@@ -383,6 +381,7 @@ bool OsWin32_DrawBitmap(HBITMAP hBMP, wxDC& dc, const wxRect& dst, const wxRect&
       free(bi);
 	  }
 	  else
+
 	  {
 		  HGDIOBJ hOldBitmap = ::SelectObject(hMemDC, hBMP);
       //::SetStretchBltMode(hDC, nDepth > 8 ? COLORONCOLOR : HALFTONE);
diff --git a/xvaga/xvaga.cpp b/xvaga/xvaga.cpp
index 82e7fb872..c70305791 100755
--- a/xvaga/xvaga.cpp
+++ b/xvaga/xvaga.cpp
@@ -1422,6 +1422,7 @@ char* xvt_cb_alloc_data(long size)
 BOOLEAN xvt_cb_close(void)
 {
 	wxTheClipboard->Close();
+	wxTheClipboard->Flush();
 	return TRUE;
 }
 
@@ -2016,11 +2017,11 @@ wxFont& TFontId::Font(wxDC* dc, WINDOW win) const
 		{
   		const wxSize ppi = dc->GetPPI();
 
-      const int nTarget = ppi.x;
-      const int cpi = 120 / nSize;
-      const wxString str('M', cpi);
+      const int nTarget10 = 10 * ppi.x;
+      const int cpi10 = 10 * 120 / nSize;
+      const wxString str('M', cpi10);
 
-      int nMin = 1, nMax = nSize*10;
+      int nMin = 1, nMax = nSize*12;  // Limiti arbitrari
       int nBest = 0;
       while (nMin <= nMax)
       {
@@ -2028,11 +2029,11 @@ wxFont& TFontId::Font(wxDC* dc, WINDOW win) const
         wxFont courier(-nFontSize, Family(), wxNORMAL, wxNORMAL, FALSE, FaceName());
 	  		dc->SetFont(courier);
 				int tw;	dc->GetTextExtent(str, &tw, NULL);
-        if (tw <= nTarget)
+        if (tw <= nTarget10)
         {
           nMin = nFontSize+1;
           nBest = nFontSize;
-          if (tw == nTarget)
+          if (tw == nTarget10)
             break;
         }
         else
@@ -2040,9 +2041,26 @@ wxFont& TFontId::Font(wxDC* dc, WINDOW win) const
       }
       if (nBest == 0)
         nBest = nMax;
+
+      // Pezza per cercare di ovviare a dimensioni assurde calcolate dai sistemi NON XP
+      bool bPrevGood = true;
+      for (int i = 15; i > 0; i--)
+      {
+        const int nFontSize = nBest-i;
+        wxFont courier(-nFontSize, Family(), wxNORMAL, wxNORMAL, FALSE, FaceName());
+	  		dc->SetFont(courier);
+				int tw;	dc->GetTextExtent(str, &tw, NULL);
+        if (tw > nTarget10 && bPrevGood)
+        {
+          nBest = nFontSize-1;
+          break;
+        }
+        bPrevGood = tw <= nTarget10;
+      }
+
       dPrintScale = double(nBest) / double(nSize);
 #ifdef LINUX
-      if (is_printer_dc(dc))
+      if (is_printer_dc(dc)) // test inutile
       	dPrintScale *= 0.1; // * wxPostScriptDC::GetResolution()) / 72.0);
 #endif
 			lastDC = dc;