// cglib04.cpp 
                     
#include <utility.h>
#include <progind.h>
#include <stdlib.h> 
#include <extcdecl.h>

#include "cglib.h"
#include "cglib04.h"

const int size  = 256;     //Lunghezza del record del TRASFER
const int sizeH = 1024;    //Lunghezza del record dell'HEADER   

const char* tracciato_AS = "cgtrc.ini";  
const char* tracciato_PC = "cgtrcpc.ini";    

const int RIC_SIZE = 512;

HIDDEN char _isam_string[RIC_SIZE];
HIDDEN char __dep[LEN_REC_HEAD];

#if XVT_OS == XVT_OS_WIN
#include <io.h>
int fremove(const char* path)
{ return _unlink(path); }
#endif

//ritorna falso se la causale non e' significativa
bool look_causale (const char* codcaus)
{
  TString16 caus = codcaus;
  if (caus == "000")
    return FALSE;
  return !caus.blank();  
}

bool format_if_zero(TString& field, int len)
{
  if (real::is_natural(field))
    field.right_just(len, '0');

  return TRUE;
}

////////////////////////////////////////////////////////////////////
// TRic_recfield                                                    
////////////////////////////////////////////////////////////////////

HIDDEN void __getfieldbuff(int l, int t, const char* recin, char *s)
{
  if (recin == NULL)
  {
    *s = '\0';
    return;
  }
  
  if (t != _alfafld && t != _datefld)
  {                   
    if (t == _intzerofld || t == _longzerofld)
    {             
      byte i = 0;
      for (char* c = (char*)recin; i < l; c++, i++)
        if (*c == ' ') *c = '0';     
        else break;
      if (i == l) 
        l = 0;  
    }
    else                            
    {
      while ((*recin == ' ') && (l))
      {
        recin++;
        l--;
      }
      if ((t != _realfld) && (t != _charfld))
      {
        while ((*recin == '0') && (l))
        {
          recin++;
          l--;
        }
      }
    }  
  }

  if (l)
  {
    strncpy(s, recin, l);
//    for (int i = l-1; i >= 0 && s[i] == ' '; i--);
//    l = byte(i+1);
  }
  s[l] = '\0'; 
  if (*s)
  {
    if (t == _datefld)
    {
      const TDate dt(atol(s));
      strcpy(s, dt.string(full));
    } else
      if (t == _boolfld)
      {
        const char ok = toupper(*s);
        if (ok == 'T' || ok == 'Y' || ok == 'S' || ok == 'X')
          strcpy(s,"X");
        else
          strcpy(s," ");
      }    
  }
} 

void setdec(char * s,int dec) 
{
  char    *s1;
  int     i, l, carry;
  
  if (strlen(s) == 0) strcpy(s, "0");
  if ((s1 = strchr(s, ',')) != NULL) *s1 = '.';
  s1 = strchr(s, '.');
  if ((dec) && (s1 == NULL))
  {
    strcat(s, ".");
    s1 = strchr(s, '.');
  }
  else
    if (!dec) 
    {
      if (s1 == NULL) return ;
      l = strlen(s1); /* occhio verificare */
      carry = (s1[1] >= '5');
      *s1 = '\0';
      while (carry)
      {
        s1--;
        if (*s1 == '-') break;
        if (*s1 == '9')
        {
          *s1 = '0';
          if (s == s1) break;
        }
        else
        {
          (*s1)++;
          carry = FALSE;
        }
      }
      if (carry)
      {
        for (i = l; i > (*s1 == '-'); i--) s[i] = s[i - 1];
        s[(*s1 == '-')] = '1';
      }
      return;
    }
  s1++;
  l = strlen(s1);
  if (l > dec)
  {
    carry = (s1[dec] >= '5');
    s1[dec] = '\0';
    while (carry)
    {
      dec--;
      if (s1[dec] == '9')
      {
        s1[dec] = '0';
        if (!dec) break;
      }
      else
      {
        s1[dec]++;
        carry = FALSE;
      }
    }
    s1--;
    while (carry)
    {
      s1--;
      if (*s1 == '-') break;
      if (*s1 == '9')
      {
        *s1 = '0';
        if (s == s1) break;
      }
      else
      {
        (*s1)++;
        carry = FALSE;
      }
    }
    if (carry)
    {
      for (i = l; i > (*s1 == '-'); i--) s[i] = s[i - 1];
      s[(*s1 == '-')] = '1';
    }
  }
  else
    while (l++ < dec) strcat(s1, "0");
}

HIDDEN void  __putfieldbuff(int l, int d, int t, const char* s, char* recout)
{
  int len, i;

  if (recout == NULL) return;

  char s2[RIC_SIZE];
  strcpy(s2, s);

  if (t == _datefld)
  {
    if (*s2)
    {
      const TDate dt(s2);
      sprintf(s2,"%8s", dt.string(ANSI));
    }
  }
  else
    if (t == _boolfld)
    {           
      const char ok = toupper(*s2);
      if (ok == 'T' || ok == 'Y' || ok == 'S' || ok == 'X')
        strcpy(s2, "T");
      else
        strcpy(s2, "F");
    }
    else
      if (t == _realfld) setdec(s2, d);

  len = strlen(s2);
  
  if (len > l) 
  {
    yesnofatal_box("Impossibile scrivere %d caratteri su di un campo di %d", (int)len, (int)l);
    return;
  }  
  
  if ((t == _intfld)     ||
      (t == _longfld)    ||
      (t == _wordfld)    ||
      (t == _realfld)    ||
      (t == _intzerofld) ||
      (t == _longzerofld)
      )
  {
    if (len == 0)
    {
      strcpy(s2, "0");
      len = 1;
    } 
    
    const char c = (t == _intzerofld || t == _longzerofld) ? '0' : ' ';
    i = 0;
    while (i < l - len - 1) recout[i++] = c;
    strncpy(&recout[l - len - 1], s2, len) ;
  }
  else
  {
    strncpy(recout, s2, len) ;
    while (len < l) recout[len++] = ' ';
  }
} 



TRic_recfield::TRic_recfield(TRectype& rec, const char* name, int from, int len) 
{      
  strcpy(_name, name);
  _rec = &rec;
  set(from, len);  
  _len = len;     
}

void TRic_recfield::set(int from, int to)

{
  int nf;
  RecDes* rd = _rec->rec_des();

  if ((nf = findfld(rd, _name)) == -1)
  {
    _p = NULL;
    _len = 0;
    _dec = 0;
    _type = _nullfld;
    yesnofatal_box("File n. %d unknown field %s", _rec->num(), _name);
  }
  else
  {
    CHECK(from >= 0, "Invalid Start");
    _p = _rec->string() + rd->Fd[nf].RecOff + from;
    _dec = rd->Fd[nf].Dec;
    _type = rd->Fd[nf].TypeF;
/*    if  (to >= 0)
    {
      CHECK(from <= to && to <= rd->Fd[nf].Len, "Invalid Range");
      _len = to - from + 1;
    }
    else _len = rd->Fd[nf].Len - from;*/
  }
}

const char* TRic_recfield::operator =(const char* s)
{
  __putfieldbuff( _len, _dec, _type, s, _p);
  _rec->setdirty();
  return s;
}

TRic_recfield::operator const char*() const
{
  __getfieldbuff( _len, _type, _p, _isam_string);
  return _isam_string;
}

// Ritorna il record di controllo del trasfer
const char* TTransfer_file::record() const 
{ 
  return __dep; 
} 

TTransfer_file::TTransfer_file(char scelta) 
{ 
  _trasfer     = NULL;    
  _tot_rec     = 0L;
  _numreg_p    = 0L;
  _numreg_piva = 0L;
  _scelta      = scelta;
  _control_rec = new TFixed_string(__dep, LEN_REC_HEAD);
  if (scelta == 'S')
    _trc.leggi_modulo(tracciato_AS);
  else
    if (scelta == 'P')
      _trc.leggi_modulo(tracciato_PC);  

  _npoccas = 0L;
}

TTransfer_file::~TTransfer_file()
{
  delete _control_rec;
  if (_trasfer) 
    fclose (_trasfer);                             
}

void TTransfer_file::close()
{
  if (_trasfer) 
    fclose(_trasfer);
}

bool TTransfer_file::open(const char* path, bool create)
{
  if (_trasfer) fclose(_trasfer);

  const char* mode = create ? "a+t" : "r+t";

  _trasfer = fopen (path, mode);
  return _trasfer != NULL;
}

const char* TTransfer_file::path(long codditta)
{
  if (codditta)
    return firm2dir(codditta);
  else
    return main_app().get_firm_dir();
}

void TTransfer_file::remove_all(bool file_ditta)
{                           
  TString sigle;
  TString dir,trasfer;
  
  if (file_ditta)    
  {
    dir << main_app().get_firm_dir();
    trasfer = dir;
    dir << HEADER;
    trasfer << "\\trasfer";
  }
  else
  {
    dir << firm2dir(0);
    trasfer = dir;
    dir << HEADER;
    trasfer << "\\trasfer";
  }
  
  if (fexist(trasfer))
    fremove(trasfer);
      
  open(dir,FALSE);
  read_control_rec();
  sigle = sigle_file();
  sigle.trim();
  close(); 
  dir = "";                                    
  if (file_ditta)
    dir << main_app().get_firm_dir();
  else
    dir << firm2dir(0);
  
  bool prima_volta = TRUE;
  
  for (int i = 0; i < sigle.len(); i++)
  {
    char sigla = sigle[i];
  
    if (prima_volta)
    {
      TString80 trasf;
      trasf << dir << HEADER;
      fremove(trasf);
      prima_volta = FALSE;
    }
    
    if (sigla == 'W')
    {
      TString80 path;
      path << dir << "\\tcaus.dbf";
      fremove(path);
      path = "";
      path << dir << "\\tcaus.cdx";
      fremove(path);
      path = "";
      path << dir << "\\trcaus.dbf";
      fremove(path);
      path = "";
      path << dir << "\\trcaus.cdx";
      fremove(path);
    }
    if (sigla == 'A')
    {
      TString80 path;
      path << dir << "\\tclifo.dbf";
      fremove(path);
      path = "";
      path << dir << "\\tclifo.cdx";
      fremove(path);
    }
    if (sigla == 'P')
    {
      TString80 path;
      path << dir << "\\tpcon.dbf";
      fremove(path);
      path = "";
      path << dir << "\\tpcon.cdx";
      fremove(path);
    }
    if (sigla == 'Z')
    {
      TString80 path;
      path << dir << "\\tmov.dbf";
      fremove(path);
      path = "";
      path << dir << "\\tmov.cdx";
      fremove(path);
      path = "";
      path << dir << "\\trmov.dbf";
      fremove(path);
      path = "";
      path << dir << "\\trmov.cdx";
      fremove(path);
    }
    if (sigla == 'U')
    {
      TString80 path;
      path << dir << "\\trmoviva.dbf";
      fremove(path);
      path = "";
      path << dir << "\\trmoviva.cdx";
      fremove(path);
      path = "";
      path << dir << "\\toccas.dbf";
      fremove(path);
      path = "";
      path << dir << "\\toccas.cdx";
      fremove(path);      
    }               
    if (sigla == 'B')
    {
      TString80 path;
      path << dir << "\\tpart.dbf";
      fremove(path);
      path = "";
      path << dir << "\\tpart.cdx";
      fremove(path);
      path = "";
      path << dir << "\\tscad.dbf";
      fremove(path);
      path = "";
      path << dir << "\\tscad.cdx";
      fremove(path);
      path = "";
      path << dir << "\\tpagsca.dbf";
      fremove(path);
      path = "";
      path << dir << "\\tpagsca.cdx";
      fremove(path);
    }    
  } 
}

bool TTransfer_file::read_control_rec()
{
  TString16     tmp;
  
  if (!exist()) return FALSE;
  
  _control_rec->spaces();
  
  // va all'inizio del file
  fseek (_trasfer, 0L, SEEK_SET); 
  
//  const word letti = fread((char*)(const char*)_control_rec,sizeof(char),sizeH,_trasfer);
  const word letti = fread(__dep, sizeof(char), sizeH, _trasfer);  
  
  _control_rec->cut(sizeH);
  
#ifdef DBG  
  if (_control_rec->len() > sizeH) error_box("Non e' possibile allocare una stringa di %d in una stringa fissa di %d caratteri", _control_rec->len(),sizeH);
#endif
  
  _tiporec  = _control_rec->sub(0,2);
  
  if (_tiporec == " 1")
  {    
    _nome_simb  = _control_rec->sub(60,70);
    _ditta      = atol(_control_rec->sub(70,75));
    _nultras    = atoi(_control_rec->sub(75,78));
    
    tmp         = _control_rec->sub(78,86);
    _dataultras = converti(tmp,TRUE);
    
    _sigle_file = _control_rec->sub(86,95);
    _nrec_file  = _control_rec->sub(95,149); 
    TString ult_file   = _control_rec->sub(240,241);
    TString key        = _control_rec->sub(241,301);
    _ult_file = ult_file.trim();
    _key      = key.trim();
    fill_index(_sigle_file,_nrec_file);
  }
  else
    return FALSE;
  
  return TRUE;
}

bool TTransfer_file::read_control_rec_t()
{
  TString16     tmp;
  
  if (!exist()) return FALSE;
  
  // va all'inizio del file
  fseek (_trasfer, 0L, SEEK_SET);
  const word letti = fread((char*)(const char*)_control_rec_t,sizeof(char),size,_trasfer);
  
  _tiporec  = _control_rec_t.sub(0,2);
  
  if (_tiporec == " 1")
  {    
    _nome_simb  = _control_rec_t.sub(15,25);
    _ditta      = atol(_control_rec_t.sub(25,29));
    _nultras    = atoi(_control_rec_t.sub(29,32));
    tmp         = _control_rec_t.sub(32,38);
    _dataultras = converti(tmp,FALSE);
    
    _sigle_file = _control_rec_t.sub(38,47);
    _nrec_file  = _control_rec_t.sub(47,101); 
    TString ult_file   = _control_rec_t.sub(240,241);
    TString key        = _control_rec_t.sub(241,256);
    _ult_file = ult_file.trim();
    _key      = key.trim();
    fill_index(_sigle_file,_nrec_file);
  }
  else
    return FALSE;
  
  return TRUE;
}

bool TTransfer_file::write_control_rec(const char* str, const int size)
{
  if (!exist()) return FALSE;
  
  fseek(_trasfer, 0, SEEK_SET);
  const int nscritti = fwrite (str,1,size,_trasfer);
  
  return TRUE;
}

const char* TTransfer_file::name(int i)
{
  TToken_string data = (TToken_string&)_index[i];
  return data.get(0);
}

long TTransfer_file::nrec(int i)      
{
  TToken_string data = (TToken_string&)_index[i];
  return data.get_long(1);
}

int TTransfer_file::lenrec(int i)
{
  TToken_string data = (TToken_string&)_index[i];
  return data.get_int(2);
}

int TTransfer_file::lenrec(char sigla)
{
  const int i = num(sigla);
  return lenrec(i);
}

long TTransfer_file::start(char sigla)
{
  const int i = num(sigla);
  return start(i);
}

long TTransfer_file::start(int i)
{
  if (i == 0)
    return 1;
  else
  {
    TToken_string data = (TToken_string&)_index[i-1];
    return data.get_long(1) + 1;
  }
}

long TTransfer_file::end(int i)
{
  TToken_string data = (TToken_string&)_index[i];
  return data.get_long(4);
}

long TTransfer_file::rec(int i)
{   
  long rec = 1;
  
  if (i > 0)
  { 
    TToken_string data = (TToken_string&)_index[i-1];
    rec = (data.get_long(1)) + 1;
  }
  
  return rec;
}

int TTransfer_file::num(char sigla)  
{
  int items = _index.items(); 
  TString16 dep;
  
  for (int i = 0; i < items; i++)
  {
    dep = name(i);
    if ( dep[0] == sigla) 
      return i; 
  }
  
  return -1;
}

void TTransfer_file::go2rec(const long recnum)
{
  readat(recnum);
}

void TTransfer_file::readat(long recnum)
{       
  long pos,offset;
  
  // name_file | numrec | lenrec | start | end      ESEMPIO
  //     w     |  100   |   82   |   0   | 8199       DI
  //     p     |  130   |   40   |  8200 | 9399     INDICE
  
  int items = _index.items();
  
  for (int i = 0;i < items;i++) 
  {      
    if (recnum <= nrec(i))       
    {                           
      if (i > 0)                
      {  
        pos    = end(i-1) + 1;
        offset = recnum - nrec(i-1);
        pos   += offset * lenrec(i);
        break;
      }
      else
      {       
        pos = recnum * lenrec(i); 
        break;                    
      }                           
    }                            
  }                              
  _curpos  = recnum;
  _curfile = name(i);
  fseek(_trasfer,pos,SEEK_SET);
} 

int TTransfer_file::read_rec_trasfer(long numrec, int size)
{
  go2rec(numrec);
  const word letti = fread((char*)(const char*)_record,sizeof(char),size,_trasfer);
  return letti;
}

char TTransfer_file::flg_agg(char sigla)
{ 
  char flag;
  
  if (sigla == 'W')
    flag = _control_rec->sub(235,236)[0];
  
  if (sigla == 'A')
    flag = _control_rec->sub(236,237)[0];
  
  if (sigla == 'P')
    flag = _control_rec->sub(237,238)[0];
  
  return flag;
}

bool TTransfer_file::numprot_att()
{ 
  char flag;
  
  flag = _control_rec->sub(238,239)[0];
  if (flag == 'X')
    return TRUE;
  else
    return FALSE;
  
  return TRUE;
}

bool TTransfer_file::numprot_pas()
{ 
  char flag;
  
  flag = _control_rec->sub(239,240)[0];
  if (flag == 'X')
    return TRUE;
  else
    return FALSE;
  
  return TRUE;
}

char TTransfer_file::flg_agg_IV(char sigla)
{
  char flag = ' ';
  
  if (sigla == 'P')
    flag = _control_rec->sub(234,235)[0];
  
  return flag;
}

void TTransfer_file::put(const char* val, const char* file, int fieldnum,long recnum)
{
  int da = go2field(fieldnum,file,recnum,FALSE);           
  _record.overwrite(val, da);
}

int TTransfer_file::write(long numrec, int size)
{
  go2rec(numrec);
  const word scritti = fwrite((char*)(const char*)_record,sizeof(char),size,_trasfer);
  return scritti;
}

void TTransfer_file::writeat(const char* str,int size,int fieldnum,const char* file)
{
  go2field(fieldnum,file);
  
  const int nscritti = fwrite (str,1,size,_trasfer);
}

void TTransfer_file::writeat(const char* str,int size,int fieldnum,const char* file, const long nrec)
{
  go2field(fieldnum,file,nrec);
  
  const int nscritti = fwrite (str,1,size,_trasfer);
}

int TTransfer_file::go2field(int fieldnum, const char* file, const long nrec, bool seek)
{
  TString key;
  int     pos_campo;                             
  const int size = 256;

  if (nrec < 0)
    readat(_curpos);  // Mi posiziono all' inizio del record
else
  readat(nrec);
  
  if (!file)
    key.format("%2s%d",(const char*)_curfile,fieldnum);
  else
    key.format("%2s%d", file, fieldnum);
  
  if (_trc.is_key((const char *) key))  
  {
    TToken_string * data = (TToken_string *) _trc.objptr(key);
    
    pos_campo = data->get_int(2);
    // NB 
    // Nel tracciato parto da 1 (per compatibilita'), 
    // la fseek() conta da 0
    pos_campo -= 1;
    
    if (seek)
    {
      //pos_campo -= 1;
      fseek(_trasfer,pos_campo,SEEK_CUR);
    }
  }
  return pos_campo;
}

void TTransfer_file::fill_index(TString& sigle_file,TString& nrec_file)
{
  TToken_string data;
  char sigla;
  long nrec,nrecp,start,end;       
  int  i;
  int  k = 0;
  int  lrec = 256;
  
  start = end = 0;
  
  nrecp = 0L;
  
  _index.destroy();

  _last_tab = 0;
  _last_mov = 0;
  
  for (i = 0; i < sigle_file.len(); i++)
  {                      
    data   = "";
    sigla  = sigle_file.mid(i,1)[0];
    nrec   = atol(nrec_file.mid(k,6));

    if (sigla == 'W' || sigla == 'P' || sigla == 'A')
    {
      _last_tab++;
      _last_mov++;
    }
    
    if (sigla == 'Z' || sigla == 'U' || sigla == 'B')
      _last_mov++;
    
    if (sigla != ' ' && nrec != 0)
    {
      data.add(sigla);
      data.add(nrec + nrecp);
      data.add(lrec);
      nrecp += nrec; 
      
      end = (nrecp * lrec) -1;
      data.add(start);
      data.add(end);
      start = end + 1;
      
      _index.add(data);
    }                            
    k += 6;
  }

  _tot_rec = nrecp;

}

void TTransfer_file::annulla_classi(int g, int c,bool conto)
{
  TLocalisamfile pcon (LF_PCON);
  bool okann = FALSE;
  
  pcon.setkey(1);
  pcon.zero();
  pcon.put("GRUPPO", g);
  pcon.put("CONTO",  c);
  
  for (pcon.read(); !pcon.eof(); pcon.next())
  {                                    
    int gruppo = pcon.get_int("GRUPPO");
    int conto  = pcon.get_int("CONTO");

    if (gruppo != g || conto != c) break;
    
    if (conto)
    {                           
      okann = TRUE;
      long sottoc = pcon.get_long("SOTTOCONTO");
      if (sottoc == 0) continue;
    }
    else
    {
      TString sez = pcon.get("SEZIVD");
      long    sottoc = pcon.get_long("SOTTOCONTO");
      
      if (sottoc == 0)
        if (sez.empty()) break;
        else           
        {
          okann = TRUE;
          continue;
        }
    }
    
    if (okann )
    {
    pcon.zero("SEZIVD");
    pcon.zero("LETTIVD");
    pcon.zero("NUMRIVD");
    pcon.zero("NUMIVD");
    pcon.zero("SEZIVDOPP");
    pcon.zero("LETTIVDOPP");
    pcon.zero("NUMRIVDOPP");
    pcon.zero("NUMIVDOPP");
    
    pcon.rewrite();
    }
  }
}

int TTransfer_file::dataes(const TDate& d, int* prevesc, TDate& finesp)
{                   
  *prevesc = 0;
  
  TTable esc("ESC");
  for (int err = esc.first(); err == NOERR; err = esc.next())
  {
    const TDate ia(esc.get("D0"));   // Data inizio esercizio
    const TDate fa(esc.get("D1"));   // Data fine esercizio
    const anno = esc.get_int("CODTAB");  
    if (d >= ia && d <= fa)
      return anno;
    *prevesc = anno;
    finesp = fa;   
  } 
  return 0;
}

char TTransfer_file::TipoConto(int g, int c)
{
  TLocalisamfile pcon (LF_PCON);
  char tipo = ' ';
  
  pcon.setkey(1);
  pcon.zero();
  pcon.put(PCN_GRUPPO,     g);
  pcon.put(PCN_CONTO,      c);
  pcon.put(PCN_SOTTOCONTO, 0l);
  if (pcon.read() == NOERR)
    tipo = pcon.get_char(PCN_TMCF);
    
  return tipo;
}

const char* TTransfer_file::numero_civico(TString& indirizzo)
{
  int i,start,end;
  bool spazio = FALSE;
  
  start = 0;
  end   = 0;
  TEMP = "";
  
  for (i = 0; i < indirizzo.len(); i++)
  {                               
    char numero = indirizzo[i];
    
    if (spazio && (isdigit(numero))) 
    {
      TEMP << indirizzo[i];
      if (start == 0)
        start = i;
      end = i;
    }  
      
    if (indirizzo[i] == ' ' || indirizzo[i] == '.')
      if (!spazio)
        spazio = TRUE;                          
      else
        if (TEMP != "") 
          break;
  }
  
  TString substr1 = "";
  TString substr2 = "";
  
  if (start != 0)
    substr1 = indirizzo.sub(0,start - 1);
  if (end != 0)  
    substr2 = indirizzo.sub(end +1);    

  if (substr1.not_empty())
    indirizzo = substr1;
  if (substr2.not_empty)
    indirizzo << substr2;
    
  return TEMP;
}

const char* TTransfer_file::cerca_comune_cap(TString& field, const TString& localita)
{             
  TLocalisamfile comuni (LF_COMUNI);
  TString cap = field; 
  bool    trovato     = FALSE;
  bool    prima_volta = TRUE;
  
  TEMP = "";
  
  if (cap.sub(2,3) == "1")
  {
    cap = cap.sub(0,3);
    cap << "00";
  }
  
  TString dencom = localita;
  
  comuni.setkey(3);
  comuni.zero();
  comuni.put(COM_CAPCOM, cap);
  
  TRectype com (comuni.curr());
  
  for (comuni.read(_isgteq); !comuni.eof(); comuni.next())
  {
    if (comuni.curr() != com) break;
    
    TString denominazione (comuni.get(COM_DENCOM));
    if (prima_volta)
    {
      TEMP = comuni.get(COM_COM);
      prima_volta = FALSE;
    }
    
    for (int i = 0; i < 3; i++)
    {
      if (dencom[i] == denominazione[i])
        trovato = TRUE;
      else
      {
        trovato = FALSE;
        break;
      }
    }         
    if (!trovato)
      continue;
    else
    {
      TEMP = comuni.get(COM_COM);
      break;
    }
  } 
  return TEMP;
}

const char* TTransfer_file::cerca_comune_den(TString& field)
{   
  TLocalisamfile comuni (LF_COMUNI);
  
  comuni.setkey(2);
  comuni.zero();
  comuni.put(COM_DENCOM, field);
  if (comuni.read() == NOERR)
    TEMP = comuni.get(COM_COM);
  else
    TEMP = "";
  
  return TEMP;
}

void TTransfer_file::write_tmp_tabelle(TString& record, bool create)
{
  TString sigla,key,str,numero,comune;
  int     numfield = 2;  //Per le tabelle il primo campo della mappa non e' significativo
                         //ai fini del trasferimento (flag di record gia trasferito).
  TMappa_trc&       trc  = mappa();
  TIsamtempfile*    file = NULL; 
  TRectype*         dep  = NULL;
  int               logicnum;
  int               campi_righe = 0;
  int               num_riga    = 1;
  TToken_string     data;
  TString           cap = "";
  TString           tmp_path;
  
  sigla     = record.mid(0,2);
  key.format("%2s%d", (const char*)sigla,numfield);
  
  if (trc.is_key((const char *) key)) 
  {    
    int logicnum_p = 0;

    do
    {  
      logicnum = trc.logicnum(key);
        
      if (logicnum != logicnum_p)
      {
        if (logicnum_p)
        {              
          _prog->addstatus(1);
          trasfer_data_tab(*file, *dep);            
          delete file;
          delete dep;
        }           
        
        if (sigla == "W1")
        {
          if (logicnum == LF_CAUSALI)
            tmp_path = _tmpcaus;
          else
            tmp_path = _tmprcaus;
        }

        if (sigla == "A1")
          tmp_path = _tmpclifo;

        if (sigla == "P1" || sigla == "P2" || sigla == "P3")
          tmp_path = _tmppcon;
  
        file = new TIsamtempfile(logicnum, tmp_path, create);
        dep  = new TRectype (logicnum);
        dep->zero();
      }                                                 
        
      logicnum_p = logicnum;

      if (logicnum == LF_RCAUSALI) 
      {
        campi_righe++;

        if (campi_righe == CAMPI_RCAUS)
        {
          TString16 gruppo(dep->get("GRUPPO"));     
          //          
          // scarta le righe non significative
          // --------------------  NB  -----------------------
          // supponiamo il GRUPPO INDISPENSABILE !!!!!!!!!!!!!
          //
          if (gruppo.not_empty()) 
          {
            dep->put("NRIGA", num_riga++);
              
            trasfer_data_tab(*file, *dep);
          }
          else
            num_riga++;
            
          campi_righe   = 1;
        } 
      }

      int     from  = trc.from(key);
      int     to    = trc.to(key);
      TString fname = trc.field_name(key); 
      int     flag  = trc.flag(key);
      TString field = record.sub(from-1,to); 
        
      //Il nostro codice registro IVA e' lungo 3: se il loro registro (lungo 1) e' alfanumerico
      //devo allinearlo a sinistra, mentre se e' numerico devo allinearlo a destra riempendolo con degli zero.      
      if (logicnum == LF_CAUSALI)
      {                          
        if (fname == "REG")
        {
          char f = field[0];
          if (isdigit(f))
            field.format("%03c", f);
          else
            field.format("%-3c", f);     
          
          int tipomov = atoi(record.sub(208,209));   // Tipo movimento del saldaconto
          dep->put(CAU_TIPOMOV, tipomov);            // sulla causale
        }
          
        if (fname == "M770")
          if (field == "0")
            field = " ";

        if (fname == "NUMDOC" || fname == "DATADOC")
        {
          if (field == "0")
            field = " ";
          else
            if (field == "1")
              field = "X";
        }
          
        if (fname == "CODCAUSIM")
          if (field == "000")
            field = "   ";                 
      }                           
        
      if (logicnum == LF_RCAUSALI && (fname == "GRUPPO" || fname == "CONTO") )
      {
        int  gruppo,conto;
        char tipo;
          
        if (fname == "GRUPPO")
          gruppo = atoi(field);
            
        if (fname == "CONTO")
        {
          conto = atoi(field);
          tipo = TipoConto(gruppo,conto);
          dep->put(RCA_TIPOCF, tipo);
        }
      }
        
      //Il tipo cliente/fornitore presente su AS400 puo' assumere come valori 1 o 2
      //mentre quello su PC C o F; devo fare la conversione.
      if (sigla == "A1") 
      {
        if (fname == "CODCF")
        {
          long codcf = atol(field);
          field.format("%6ld", codcf);
        }
        if (fname == "TIPOCF")
        {
          if (field == "1")
            field = "C"; 
            
          if (field == "2")
            field = "F";
        }
        //Il tipo persona (fisica/giuridica) su AS400 puo' assumere come valori 1 e 0
        //mentre quello su PC F o G; devo fare la conversione.
        if (fname == "TIPOPERS")
        {
          if (field == "1")
            field = "F";
            
          if (field == "0")
            field = "G";
        }        
          
        //Il codice pagamento su AS400 e' un alfanumerico di due, mentre su PC e' un
        //alfanumerico di 4 trattato con il flag Z. Dunque in ricezione se si tratta
        //di un numero va riempito con degli 0. Se si tratta di un alfa va allineato a destra.                       
        if (fname == "CODPAG")
        { 
          TString f = field;
          //if (real::is_natural(f))
          //  field.format("%04s", (const char*) f);
          //else
            field.format("%-4s", (const char*) f);
        }
          
        if (fname == "INDCF")
        {            
          field = field.rtrim();
          if (field != "")
          {
            numero = numero_civico(field);
            dep->put(CLI_CIVCF, (const char*)numero);
          }
        }
          
        if (fname == "CAPCF")
        {
          if (field == "00000")
            field = "     ";
          else
            cap = field;
        }
          
        if (fname == "LOCALITACF")
        {
          comune = "";
            
          if (cap.not_empty())
            comune = cerca_comune_cap(cap,field);
          if (comune.empty())
            comune = cerca_comune_den(field);
          if (comune.not_empty())
          {
            dep->put(CLI_COMCF, comune);
            field = "";
          }
        } 
          
        if (fname == "ALLEG")
        {
          if (field == "0")
            field = " "; 
          if (field == "2") 
            dep->put("OCCAS", (const char*) "X");                      
              
        }  
        if (fname == "PAIV")
          if (field == "00000000000")
            field = " ";    
      }
        
      //Quando ricevo la IV direttiva del piano dei conti per evitare che nell'archivio,
      //in caso di numero romano vuoto, venga memorizzato la stringa letta sul trasfer ("000"),
      //vuoto la stringa prima di fare la put.
      if (sigla == "P2" || sigla == "P3" || sigla == "P1")
      {
        if (fname == "GRUPPO")
        {
          int gruppo = atoi(field);
          field.format("%3d", gruppo);
        }                             
        if (fname == "CONTO") 
        {
          int conto = atoi(field);
          field.format("%3d", conto);
        }                            
        if (fname == "SOTTOCONTO")
        {
          long sottoc = atol(field);
          field.format("%6ld", sottoc);
        }
      }
      if (sigla == "P2" || sigla == "P3")
      { 
        if (fname == "STSOTTBIL")
        {
          if (field == "0")
            field = " ";
          else
            if (field == "1")
              field = "X";
        }
 
        if (fname == "NUMRIVD" || fname == "NUMRIVDOPP")
        {
          if (field == "000")
            field = "";
        }
        if (fname == "SEZIVD" || fname == "SEZIVDOPP")
        {
          if (field == " ")
            field = "0";
        }
      } 
        
      dep->put(fname, (const char*)field);                      

      numfield++;
      key.format("%2s%d", (const char*) sigla,numfield);
    }
    while (trc.is_key((const char*) key));
      
    if (logicnum == LF_RCAUSALI) 
    { 
        campi_righe++;

        if (campi_righe == CAMPI_RCAUS)
        {
          TString16 gruppo(dep->get("GRUPPO"));     
          //          
          // scarta le righe non significative
          // --------------------  NB  -----------------------
          // supponiamo il GRUPPO INDISPENSABILE !!!!!!!!!!!!!
          //
          if (gruppo.not_empty()) 
          {
            dep->put("NRIGA", num_riga++);
            trasfer_data_tab(*file, *dep);
          }                                                
          else
            num_riga++;
            
          campi_righe   = 1;
        }  
    }
    else                      
    {
      _prog->addstatus(1);
      trasfer_data_tab(*file, *dep);  
    }
      
    delete file;
    delete dep;
  } // if (trc.is_key((const char*) key))
}
                                
int TTransfer_file::trasfer_data_tab(TIsamtempfile& file, TRectype& dep)
{ 
  file.zero();
  file.curr() = dep;
      
  if (file.read() == NOERR)     
  {   
    file.zero();
    file.curr() = dep;
    file.rewrite();
  }
  else
  {
    file.zero();
    file.curr() = dep;     
    file.write();    
  }
  
  return 0;
}

int TTransfer_file::annoes_datacomp(const TString& record, TDate& datacomp)
{ 
  TString tmp;   
  int     segn;
  int     ae = 0;
  
  tmp          = record.sub(15,21);
  TString data = converti(tmp,FALSE);
  _datareg     = data;
  segn         = atoi(record.sub(21,22));  
  
  ae = date2esc(_datareg);
  
  if (ae != 0)
  {
    if (segn == 0)
      datacomp = _datareg;
  
    if (segn == 1)
    {                  
      if (ae)
        ae -= 1;
      
      datafine_esprec(ae,datacomp);
    } 
  }
  else
  {
    int ae = _datareg.year();
    
    if (segn == 0)
      return ae;
      
    if (segn == 1)
      return (ae - 1);
  }
  
  return ae;
}
               
void TTransfer_file::decimali(TString& campo, int dec)
{
  int l = campo.len();
  
  if (!l) return;
  
  int p = l - dec;
  campo.insert(".",p);
}                      

int TTransfer_file::strip_zero(TString& importo)
{
  TString16 app;
  
  int size = importo.len();
  
  for (int i = 0; i < size; i++)
    if (importo[i] != '0') break;
    
  if (i > 0)
  {
    app = importo.mid(importo[i] == '.' ? i - 1 : i);
    importo = app;
  }               
  
  return (i ? i - 1 : i);
}

bool TTransfer_file::my_isdigit(unsigned char ch)
{
  return (ch >= '0' && ch <= '9');
}
                                                 
int TTransfer_file::look(unsigned char carattere)
{
  for (int i = 0; i < 10; i++)
    if (_tabella[i] == carattere)
      return i;
      
  return -1;
}             
                                                  
void TTransfer_file::negativo(TString& importo)
{                           
  strip_zero(importo);
  
  int size = importo.len();
  
  if (!size) return;
  
  unsigned char last = importo[size - 1];
  
  if (!my_isdigit(last))
  {     
    int new_last = look(last);
    TString16 dep; dep << new_last;
    if (new_last >= 0) 
    {
      importo[size - 1] = dep[0];
      importo.insert("-");  
    }
  }
}

void TTransfer_file::write_tmp_movPN(TString& record,bool create)
{
  TString sigla,key,str,codreg;
  int     numfield = 3; //Per i movimenti i primi due campi della mappa non sono significativi
  //ai fini del trasferimento (flag record gia trasferito e nuovo ultimo numero di registrazione). 
  TMappa_trc&       trc  = mappa();
  TIsamtempfile*    file = NULL; 
  TRectype*         dep  = NULL;
  int               logicnum;
  TDate             datacomp;
  TString           nreg;
  int               fnrmov = 13;
  TString           tmp_path,tipodoc;
  real              importo = ZERO;
  
  int solo_sezionale = atoi(record.mid(218,1));
  if (solo_sezionale != 1)
  {  
  sigla     = record.mid(0,2);
  key.format("%2s%d", (const char*)sigla,numfield);
    
  if (trc.is_key((const char *) key)) 
  {    
    int logicnum_p = 0;             

    _numreg = atol(record.sub(2,8));
      
    if (_numreg == _numreg_p)
    {
      numfield = fnrmov;
      key.format("%2s%d", (const char*)sigla,numfield);
    }
      
    _annoes   = annoes_datacomp(record,datacomp); 
    _numreg_p = _numreg;   

    do
    {  
      logicnum = trc.logicnum(key);
          
      if (logicnum != logicnum_p)
      {
        if (logicnum_p)
        {
          trasfer_data_mov(*file, *dep);
          delete file;
          delete dep;
        }

        if (sigla == "Z1")
        {
          if (logicnum == LF_MOV)
            tmp_path = _tmpmov;
          else
            tmp_path = _tmprmov;
        }
        
        file = new TIsamtempfile(logicnum, tmp_path, create);
        dep  = new TRectype (logicnum);
        dep->zero();
          
        logicnum_p = logicnum;                                                
      }    
      
      int     from  = trc.from(key);
      int     to    = trc.to(key);
      TString fname = trc.field_name(key); 
      TString field = record.sub(from-1,to); 
      int     flag  = trc.flag(key);
      int     dec   = trc.flag_bis(key);
          
      TRecfield campo (*dep,fname);
      if (campo.type() == _realfld)
        negativo(field);

      if (flag == 3)
      { 
        if (dec > 0)
          decimali(field,dec);
            
        real appoggio (field);
        field = appoggio.string();
      }
            
      if (logicnum == LF_MOV)
      {
        if (fname == "REG")
        {                         
          if (real::is_natural(field))
            field.format("%03s", (const char*) field);
          else
            field.format("%-3s", (const char*) field);
        }                           

        //Il codice pagamento su AS400 e' un alfanumerico di due, mentre su PC e' un
        //alfanumerico di 4 trattato con il flag Z. Dunque in ricezione se si tratta
        //di un numero va riempito con degli 0. Se si tratta di un alfa va allineato a destra.                       
        if (fname == "CODPAG")
        { 
          TString f = field;
          //if (real::is_natural(f))
          //  field.format("%04s", (const char*) f);
          //else
            field.format("%-4s", (const char*) f);
        }
        
        if (fname == "CODCAUS")
        {
          if (field == "000")
            field = "";
          
          int nr = atoi(record.sub(8,10));
          if (nr == 1)
          {
            TString descr = record.sub(44,74);
            dep->put(RMV_DESCR, descr);        // Descrizione della prima riga riportata sulla testata
          }
        } 
        
        if (fname == "TIPODOC")
          tipodoc = field;          
      }

      if (fname == "IMPORTO")
      {
        real imp = real::ita2eng(field);  
        importo = imp;
      }  
      
      if (logicnum == LF_RMOV)
      {
        if (fname == "NUMRIG")
        {
          int nriga = atoi(field);
          field.format("%3d", nriga);
        }                            
        if (fname == "GRUPPO" || fname == "GRUPPOC")
        {
          int gruppo = atoi(field);
          field.format("%3d", gruppo);
        }        
        if (fname == "CONTO" || fname == "CONTOC")
        {
          int conto = atoi(field);
          field.format("%3d", conto);
        }                            
        if (fname == "SOTTOCONTO" || fname == "SOTTOCONTC")
        {
          long sottoc = atol(field);
          field.format("%6ld", sottoc);
        }
      }
      
      if (logicnum == LF_MOV && (fname == "NUMREG" || flag == 2) ) 
      {                       
        if (fname == "NUMREG") 
        {
          dep->put(MOV_ANNOES,   _annoes);                                     
          dep->put(MOV_NUMREG,   _numreg);
          dep->put(MOV_DATAREG,  _datareg);
          dep->put(MOV_DATACOMP, datacomp);  
          int annoiva = _datareg.year();
          dep->put(MOV_ANNOIVA,  annoiva);
        }
        if (flag == 2)
        {
          TString f = converti(field,FALSE);
          dep->put(fname,f);
        }
      }
      else  
        if (logicnum == LF_RMOV && (fname == "NUMREG" || fname == "NUMRIG") ) 
        {                        
          if (fname == "NUMREG")
          {   
            dep->put(RMV_ANNOES,  _annoes);                                     
            dep->put(RMV_NUMREG,  _numreg);
          }

          if (fname == "NUMRIG")
          {
            dep->put(RMV_NUMRIG,  field);  
            dep->put(RMV_DATAREG, _datareg);
          }          
        }
        else
          dep->put(fname, field);
          
      numfield++;
      key.format("%2s%d", (const char*) sigla,numfield);
    }
    while (trc.is_key((const char*) key));
        
    _prog->addstatus(1);
    
    if (importo != ZERO)
      trasfer_data_mov(*file, *dep);      
        
    delete file;
    delete dep;
  } // if (trc.is_key((const char*) key))
  } // if (solo_sezionale != 1)
}

int TTransfer_file::trasfer_data_mov(TIsamtempfile& file, TRectype& dep)
{  
  file.zero();
  file.curr() = dep;
                      
  if (file.read() == NOERR)     
  { 
    file.zero();
    file.curr() = dep;
    file.rewrite();
  }
  else
  {
    file.zero();
    file.curr() = dep;     
    file.write();    
  }
  return 0;
}

int TTransfer_file::cerca_annoes(long numreg,TString& tipodoc)
{
  TString80 tmpmov = "%";
  tmpmov  << main_app().get_firm_dir();
  tmpmov << "\\" << TEMP_MOV;
  TIsamtempfile tmov (LF_MOV, tmpmov, 0);  

  int anno = 0;
  
  tmov.setkey(1);
  tmov.zero();
  tmov.put(MOV_NUMREG, numreg);
  if (tmov.read() == NOERR)                                  
  {
    anno    = tmov.get_int(MOV_ANNOES);
    tipodoc = tmov.get    (MOV_TIPODOC);
  }
  
  return anno;
}

/*void TTransfer_file::ricerca_comune(const TString& com)
{
  TLocalisamfile comuni (LF_COMUNI);
  
  comuni.setkey(2);
  comuni.zero();
  comuni.put(COM_DENCOM, com);
  if (comuni.read() == NOERR)
    _cod_com = comuni.get(COM_COM);
  else
    _cod_com = "";
}*/

const char* TTransfer_file::scrivi_occasionali(const TString& record)
{
  TString cfpi,ragsoc,ind,com,cap,app,civ; 
  int     err;
  
  ragsoc = record.sub(61,86);
  cfpi   = "";               
  civ    = "";
  
  if (ragsoc.trim().empty()) return cfpi;
  
  _npoccas++;
  
  ind    = record.sub(86,108);
  com    = record.sub(108,126);
  cap    = record.sub(126,131);
  
  ind    = ind.rtrim();
  if (ind != "")
    civ = numero_civico(ind);
  
  app = "RIC";
  cfpi.format("%3s%13ld", (const char*)app,_npoccas);
  
  //ricerca_comune(com);
  _cod_com = "";
            
  if (cap.not_empty())
    _cod_com = cerca_comune_cap(cap,com);
  if (_cod_com.empty())
    _cod_com = cerca_comune_den(com);
  
  _toccas->setkey(1);
  _toccas->zero();
  _toccas->put("CFPI",   cfpi);
  _toccas->put("RAGSOC", ragsoc);
  _toccas->put("INDIR",  ind);
  _toccas->put("CIV",    civ);
  _toccas->put("CAP",    cap);  
  if (_cod_com != "")
    _toccas->put("COM", _cod_com);
  
  err = _toccas->write();
  
  if (err == _isreinsert)
    err = _toccas->rewrite();
    
  return cfpi;
}

void TTransfer_file::write_tmp_movIVA(TString& record, bool create)
{
  TString sigla,key,str;
  int     numfield = 3; //Per i movimenti i primi due campi della mappa non sono significativi
  //ai fini del trasferimento (flag record gia trasferito e nuovo ultimo numero di registrazione).  
  TMappa_trc&       trc  = mappa();
  TIsamtempfile*    file = NULL; 
  TRectype*         dep  = NULL;
  int               logicnum;
  TString           nreg,tipodoc;
  int               fnrmiva = 11;                          
  TString           tmp_path;
  
  sigla     = record.mid(0,2);
  key.format("%2s%d", (const char*)sigla,numfield);
    
  if (trc.is_key((const char *) key)) 
  {
    TString cfpi;
      
    int logicnum_p = 0;             
      
    _numreg = atol(record.sub(2,8));
      
    if (_numreg == _numreg_piva)
    {
      numfield = fnrmiva;
      key.format("%2s%d", (const char*)sigla,numfield);
    }
    else
      cfpi = scrivi_occasionali(record);                       
                           
    _numreg_piva = _numreg;
        
    do
    {  
      logicnum = trc.logicnum(key);
          
      if (logicnum != logicnum_p)
      {
        if (logicnum_p)
        {
          trasfer_data_moviva(*file, *dep, logicnum_p);
          delete file;
          delete dep;
        }

        if (sigla == "U1")
        { 
          if (logicnum == LF_MOV)                            
          {
            tmp_path = _tmpmov;
            file = new TIsamtempfile(logicnum, tmp_path, 0);
          }
          else
          {
            tmp_path = _tmprmoviva;
            file = new TIsamtempfile(logicnum, tmp_path, create);
          }
        }

        dep  = new TRectype (logicnum);
        dep->zero();
      }                                                 
          
      logicnum_p = logicnum;                                                
          
      int     from  = trc.from(key);
      int     to    = trc.to(key);
      TString fname = trc.field_name(key); 
      TString field = record.sub(from-1,to); 
      int     flag  = trc.flag(key);
      int     dec   = trc.flag_bis(key);
          
      if (logicnum == LF_MOV && fname == "TOTDOC")
      {
        numfield++;
        key.format("%2s%d", (const char*) sigla,numfield);
        continue;
      }
      
      TRecfield campo (*dep,fname);
      if (campo.type() == _realfld)
        negativo(field);
                                                     
      if (flag == 3)
      {
        if (dec > 0)
          decimali(field,dec);

        real appoggio (field);
        field = appoggio.string();  
      }                           
      
      if (logicnum == LF_RMOVIVA)
      {
        if (fname == "NUMRIG")
        {
          int nriga = atoi(field);
          field.format("%3d", nriga);
        }         
      }
      
      if (logicnum == LF_MOV && ( fname == "NUMREG" || flag == 2 ) ) 
      {  
        if (fname == "NUMREG")
        {
          dep->put("NUMREG",   _numreg);
          dep->put("OCFPI",    cfpi);
        }
            
        if (flag == 2)
        {
          TString f = converti(field,FALSE);
          dep->put(fname,f);
        }                                       
      }
      else
        if (logicnum == LF_RMOVIVA && fname == "NUMREG")
        {
          int annoes = cerca_annoes(_numreg,tipodoc);                    
          dep->put("ANNOES",   annoes);                                     
          dep->put("NUMREG",   _numreg);
        }
        else
          dep->put(fname, field);          
      
      numfield++;
      key.format("%2s%d", (const char*) sigla,numfield);
    }
    while (trc.is_key((const char*) key));
        
    _prog->addstatus(1);                                  
    trasfer_data_moviva(*file, *dep, logicnum_p);      
        
    delete file;
    delete dep;
  } // if (trc.is_key((const char*) key))
}

int TTransfer_file::trasfer_data_moviva(TIsamtempfile& file, TRectype& dep, int ln)
{   
  file.zero();
  file.curr() = dep;
                      
  if (file.read() == NOERR)     
  { 
    if (ln == LF_MOV)
    { 
      TDate   data74ter (dep.get_date(MOV_DATA74TER));
      TString codval    (dep.get     (MOV_CODVALI));   
      TString ocfpi     (dep.get     (MOV_OCFPI));
      long    codcf     = dep.get_long(MOV_CODCF);
      real    cambioi   (dep.get_real(MOV_CAMBIOI));
      real    corrlire  (dep.get_real(MOV_CORRLIRE));
      real    corrvaluta(dep.get_real(MOV_CORRVALUTA));
      
      file.put(MOV_DATA74TER, data74ter);
      file.put(MOV_CODVALI,   codval);            
      file.put(MOV_OCFPI,     ocfpi);
      file.put(MOV_CODCF,     codcf);
      file.put(MOV_CAMBIOI,   cambioi);
      file.put(MOV_CORRLIRE,  corrlire);
      file.put(MOV_CORRVALUTA,corrvaluta);
      
      file.rewrite();
    }
    else
    {
      file.zero();
      file.curr() = dep;
      file.rewrite();
    }
  }
  else
  {
    file.zero();
    file.curr() = dep;     
    file.write();    
  }
  
  return 0;
}                    

void TTransfer_file::tipo_anagrafica(TString& record,TString& tipoc)
{
  char tipo = (record.sub(15,16))[0];
  switch (tipo)
  {
    case '1':
      tipoc = "C";
      break;
    case '2':
      tipoc = "F";
      break;
    case '3': 
      tipoc = " ";
    default:
      break;
  };              
}

int TTransfer_file::ultima_riga_partita(TString& record)
{                     
  TString tipoc;                         
  int  riga = 0;
  
  TRecnotype rec = _tpart->recno();
  TIsamtempfile& tpart = *_tpart;
  
  tipo_anagrafica(record,tipoc);
  
  int  gruppo = atoi(record.sub(16,18));
  int  conto  = atoi(record.sub(18,20));
  long sottoc = atol(record.sub(20,26));
  
  tpart.setkey(1);
  tpart.zero();
  tpart.put(PART_TIPOCF,     tipoc);
  tpart.put(PART_GRUPPO,     gruppo);
  tpart.put(PART_CONTO,      conto);
  tpart.put(PART_SOTTOCONTO, sottoc);
  tpart.put(PART_ANNO,       _annoSC);
  tpart.put(PART_NUMPART,    _numpartSC);
  
  TRectype partita (tpart.curr());
  
  for (tpart.read(_isgteq); !tpart.eof(); tpart.next())
  {      
    TString part_rec  = partita.get(PART_NUMPART);      //CONF
    TString part_file = tpart.get(PART_NUMPART);
    if (tpart.curr() != partita || part_file != part_rec) break;
    
    riga = tpart.get_int(PART_NRIGA);
  }                                  
  
  _tpart->readat(rec);
  
  return riga+1;
}

void TTransfer_file::write_tmp_movSC(TString& record, bool create)
{             
  TString annostr;
  
  _nregSC    = atol(record.sub(2,8));
  _numrigSC  = atoi(record.sub(8,10));
  TString app (record.sub(26,28));
  int     anno = atoi(app);
  if (anno <= 25)
    annostr = "20"; 
  else 
    annostr = "19";
  annostr << app;
  _annoSC    = atoi(annostr);
  _numpartSC = record.sub(28,35);

  int tipomov = atoi(record.sub(37,38));
    
  if (_nregSC != _nregSC_p || _numrigSC != _numrigSC_p || 
      _annoSC != _annoSC_p || _numpartSC != _numpartSC_p)
    _nrigaSC = ultima_riga_partita(record);
  
  _nregSC_p    = _nregSC;
  _numrigSC_p  = _numrigSC;
  _annoSC_p    = _annoSC;
  _numpartSC_p = _numpartSC;                         
  
  partita(record);          
  if (tipomov == 1)
    scadenza(record);    
  else
    pagsca(record);
        
  _prog->addstatus(1);                                  
}

void TTransfer_file::calcola_imposta(TString& field, real& imposta)
{                                    
  TString       buffer;
  
  TRecnotype rec = _ttab->recno();
  TIsamtempfile& tab = *_ttab; 
  
  long nreg = atol(field);
  TString app (format("%2s%06ld", (const char*) "U1", nreg));

  TRic_recfield recf (tab.curr(), "S0", 0, 256);
    
  tab.zero();
  tab.put("CODTAB", app);

  TRectype rectab (tab.curr());
    
  for (tab.read(); !tab.eof(); tab.next())
  {
    if (tab.curr() > rectab) break;
    
    buffer = (const char*) recf;
                                  
    TString app (buffer.sub(34,43));
    negativo(app);
    real imp (app);
    imposta += imp;                              
  } 
  _ttab->readat(rec);
}


bool TTransfer_file::solo_SC(TString& field)
{                                           
  TIsamtempfile tmov (LF_MOV, _tmpmov, FALSE);
  
  long nreg = atol(field);
                
  tmov.setkey(1);              
  tmov.zero();   
  tmov.put(MOV_NUMREG, nreg);
  if (tmov.read() == NOERR)
    return FALSE;      
  
  return TRUE;  
}

void TTransfer_file::calcola_impdocval(long nreg,int nrig,TString& record)
{
  int key = _tpart->getkey();      
  TRecnotype rec = _tpart->recno();
  TIsamtempfile& part = *_tpart;
  bool prima_volta = TRUE;
  real doc,val;
  
  doc = ZERO;
  val = ZERO;
 
  real itdoc (record.sub(116,127));
  TString app (record.sub(127,140));
  negativo(app);
  decimali(app,3);
  real itval (app);
      
  part.setkey(2);
  part.zero();
  part.put(PART_NREG,   nreg);
  part.put(PART_NUMRIG, nrig);
      
  TRectype partita (part.curr());
      
  for (part.read(); !part.eof(); part.next())
  { 
    TString part_rec  = partita.get(PART_NUMPART);
    TString part_file = part.get(PART_NUMPART);       
    
    if (part.curr() > partita || part_file != part_rec) break;
    
    if (prima_volta )
    {    
      doc = part.get_real(PART_IMPTOTDOC) + itdoc;
      val = part.get_real(PART_IMPTOTVAL) + itval;
      prima_volta = FALSE;
    }
        
    part.put(PART_IMPTOTDOC, doc);
    part.put(PART_IMPTOTVAL, val);  
    part.setkey(1);
    part.rewrite();
    part.setkey(2);
  }                
  _tpart->readat(rec);
  _tpart->setkey(key);
}


void TTransfer_file::partita(TString& record)
{                          
  TMappa_trc& trc  = mappa();
  TString     sigla,key;
  int         numfield;     // Campo di partenza del saldaconto su cgtrc.ini
  TString     tipoc;
  bool        solo_saldaconto = FALSE;                        
  static long numreg;
  static int  numrig;
  
  int tipomov = atoi(record.sub(37,38));

  if (tipomov == 1)
    numfield = 1;
  else
    if (tipomov == 2)
      numfield = 50;
    else 
      if (tipomov == 3 || tipomov == 4 || tipomov == 5 || tipomov == 6)
        numfield = 100;
         
  sigla     = record.mid(0,2);
  key.format("%2s%d", (const char*)sigla,numfield);
    
  if (trc.is_key((const char *) key)) 
  {    
    _deppart->zero();

    tipo_anagrafica(record,tipoc);

    do
    {
      int     from  = trc.from(key);
      int     to    = trc.to(key);
      TString fname = trc.field_name(key); 
      TString field = record.sub(from-1,to); 
      int     flag  = trc.flag(key);
      int     dec   = trc.flag_bis(key);

      TRecfield campo (*_deppart,fname);
      if (campo.type() == _realfld)
        negativo(field);

      if (flag == 3)
      { 
        if (dec > 0)
          decimali(field,dec);
            
        real appoggio (field);
        field = appoggio.string();
      }

      if (fname == "TIPOC")
        field = tipoc;

      if (fname == "GRUPPO" || fname == "CONTO" || fname == "GRUPPOCL" || fname == "CONTOCL")
      {
        int app = atoi(field);
        field.format("%3d", app);
      }        
      if (fname == "SOTTOCONTO")
      {
        long sottoc = atol(field);
        field.format("%6ld", sottoc);
      }
      if (fname == "ANNO")
      {
        TString app  = field;
        int     anno = atoi(field);
        if (anno <= 25)
        {
          field = "20"; 
          field << app;
        }
        else 
        {
          field = "19";
          field << app; 
        }
      }
      if (fname == "NRIGA") 
      {
        TString app (format("%4d", _nrigaSC));
        field = app;        
      }
      if (fname == "NREG")
      { 
        solo_saldaconto = solo_SC(field);
        if (!solo_saldaconto)
        {
          long app = atol(field);
          field.format("%7ld", app);    
/*          real imposta;  
        
          if (tipomov == 1)   // L'imposta va calcolata solo in caso di FATTURA
          {
            calcola_imposta(field,imposta);
            _deppart->put("IMPOSTA", imposta);  
          }   */
        }
        else 
          field = "";               
        numreg = atol(field);  
      }
      if (fname == "NUMRIG")
      { 
        if (!solo_saldaconto) 
        {
          int app = atoi(field);
          field.format("%3d", app);      
        }
        else
          field = "";        
        numrig = atoi(field);  
      }
      if (fname == "REG")
      {                         
        if (real::is_natural(field))
          field.format("%03s", (const char*) field);
        else
          field.format("%-3s", (const char*) field);
      }                           

      if (fname == "CODCAUS")
        if (field == "000" || solo_saldaconto)
          field = "";
      
      if (flag == 2)
      {
        TString f = converti(field,FALSE);
        _deppart->put(fname,f);
      }
      else
        _deppart->put(fname, field);

      numfield++;
      key.format("%2s%d", (const char*) sigla,numfield);
    }
    while (trc.is_key((const char*) key));
  }  // if (trc.is_key((const char*) key)
  
  _tpart->setkey(1);
  _tpart->zero();
  _tpart->curr() = *_deppart;
  if (_tpart->read() != NOERR)
  {     
    _tpart->zero();
    _tpart->curr() = *_deppart;
    _tpart->write();
  }
  
//  if (tipomov != 1 && tipomov != 4) 
//    calcola_impdocval(numreg,numrig,record);
}

void TTransfer_file::calcola_importo(TString& record)
{                               
  TString tipoc;
  TRecnotype rec = _tpart->recno();
  TIsamtempfile& part = *_tpart;
  
  tipo_anagrafica(record,tipoc);
  
  part.setkey(1);
  part.zero();
  part.put(PART_TIPOCF,     tipoc);
  part.put(PART_GRUPPO,     (atoi(record.sub(16,18))));
  part.put(PART_CONTO,      (atoi(record.sub(18,20))));
  part.put(PART_SOTTOCONTO, (atol(record.sub(20,26)))); 
  part.put(PART_ANNO,       _SCAanno);
  part.put(PART_NUMPART,    record.sub(28,35));
  part.put(PART_NRIGA,      _nrigaSC);
  if (part.read() == NOERR)
  { 
    _imp    += part.get_real(PART_IMPORTO);
    _impval += part.get_real(PART_IMPORTOVAL);
    part.put(PART_IMPORTO,    _imp);
    part.put(PART_IMPORTOVAL, _impval);
    
    int err = part.rewrite();  
    _imp    = ZERO;
    _impval = ZERO;
  }    
  _tpart->readat(rec);    
}

void TTransfer_file::scadenza(TString& record)
{                          
  TMappa_trc& trc  = mappa();
  TString     sigla,key,app_imp,app_val;
  int         numfield = 150;
  TString     tipoc;              
  static bool prima_volta = TRUE;          

  int tipomov = atoi(record.sub(37,38));
   
  sigla     = record.mid(0,2);
  key.format("%2s%d", (const char*)sigla,numfield);
    
  if (trc.is_key((const char *) key)) 
  {    
    _depscad->zero();

    tipo_anagrafica(record,tipoc);

    do
    {
      int     from  = trc.from(key);
      int     to    = trc.to(key);
      TString fname = trc.field_name(key); 
      TString field = record.sub(from-1,to); 
      int     flag  = trc.flag(key);
      int     dec   = trc.flag_bis(key);

      TRecfield campo (*_depscad,fname);
      if (campo.type() == _realfld)
        negativo(field);

      if (flag == 3)
      { 
        if (dec > 0)
          decimali(field,dec);
            
        real appoggio (field);
        field = appoggio.string();
      }
      
      if (fname == "IMPORTO")
        app_imp = field;
      if (fname == "IMPORTOVAL")
        app_val = field;
        
      if (fname == "TIPOC")
        field = tipoc;

      if (fname == "GRUPPO" || fname == "CONTO")
      {
        int app = atoi(field);
        field.format("%3d", app);
      }        
      if (fname == "SOTTOCONTO")
      {
        long sottoc = atol(field);
        field.format("%6ld", sottoc);
      }
      if (fname == "ANNO")
      {  
        TString app  = field;
        int     anno = atoi(field);
        if (anno <= 25)
        {
          field = "20"; 
          field << app;
        }
        else 
        {
          field = "19";
          field << app; 
        }
        _annoSCA = atoi(field);
      }
      if (fname == "NRIGA") 
      {
        TString app (format("%4d", _nrigaSC));
        field = app;        
      }

      //Il codice pagamento su AS400 e' un alfanumerico di due, mentre su PC e' un
      //alfanumerico di 4 trattato con il flag Z. Dunque in ricezione se si tratta
      //di un numero va riempito con degli 0. Se si tratta di un alfa va allineato a destra.                       
      if (fname == "CODPAG")
      { 
        TString f = field;
        field.format("%-4s", (const char*) f);
      }

      if (flag == 2)
      {
        TString f = converti(field,FALSE);
        _depscad->put(fname,f);
      }
      else
        _depscad->put(fname, field);

      numfield++;
      key.format("%2s%d", (const char*) sigla,numfield);
    }
    while (trc.is_key((const char*) key));
  }  // if (trc.is_key((const char*) key)
  
  _tscad->setkey(1);
  _tscad->zero();
  _tscad->curr() = *_depscad;
  
  if (_tscad->read() == NOERR)     
  { 
    _tscad->zero();
    _tscad->curr() = *_depscad;
    _tscad->rewrite();
  }
  else
  {
    _tscad->zero();
    _tscad->curr() = *_depscad;     
    _tscad->write();    
  }                                      

  if (prima_volta)
  {
    _SCAnreg_p    = -1;
    _SCAnumrig_p  = -1;
    _SCAanno_p    = -1;
    _SCAnumpart_p = "-1";
  }
  
  TString annostr;
  
  _SCAnreg      = atol(record.sub(2,8));
  _SCAnumrig    = atoi(record.sub(8,10));
  TString app (record.sub(26,28));
  int     anno = atoi(app);
  if (anno <= 25)
    annostr = "20"; 
  else 
    annostr = "19";
  annostr << app;
  _SCAanno      = atoi(annostr);
  _SCAnumpart   = record.sub(28,35);
  real imp (app_imp);
  real val (app_val);
  _imp    = imp;
  _impval = val;
//  calcola_importo(record);  
}

int TTransfer_file::recupera_scadenze(TString& record,TString& tipo)
{
  TRecnotype rec = _tscad->recno();
  TIsamtempfile& scad = *_tscad;
  int num_scad = 0;   
  TString recs,file;
  
  int rata = atoi(record.sub(35,37));
  
  scad.setkey(1);
  scad.zero();
  scad.put(SCAD_TIPOCF,     tipo);
  scad.put(SCAD_GRUPPO,     (atoi(record.sub(16,18))));
  scad.put(SCAD_CONTO,      (atoi(record.sub(18,20))));
  scad.put(SCAD_SOTTOCONTO, (atol(record.sub(20,26)))); 
  scad.put(SCAD_ANNO,       _annoSCA);
  scad.put(SCAD_NUMPART,    record.sub(28,35));
  
  TRectype scadenza (scad.curr());
  
  for (scad.read(); !scad.eof(); scad.next())
  {                
    recs = scadenza.get(SCAD_NUMPART);
    file = scad.get(SCAD_NUMPART);

    if (scad.curr() != scadenza || file != recs) break;
    
    if (scad.get_int(SCAD_NRATA) != rata) continue;
    
    num_scad++; 
    _nrigaSCA = scad.get_int(SCAD_NRIGA);
    _nrataSCA = scad.get_int(SCAD_NRATA);
  }                                                                               
  _tscad->readat(rec);

  return num_scad;
}

char TTransfer_file::what_is_this(TString& record,TString& tipo)
{ 
  TRecnotype rec = _ttab->recno();
  TIsamtempfile& ttab = *_ttab;
  const word size = 256;
  TString    buffer(size);
  
  char caso = 'p';

  int     tipomov = atoi(record.sub(37,38));
  
  if (tipomov != 2 && tipomov != 4)
  { 
    TRic_recfield recf (ttab.curr(), "S0", 0, 256);  
    
    long    nreg    = atol(record.sub(2,8));
    int     nriga   = atoi(record.sub(8,10));
    int     anno    = atoi(record.sub(26,28));
    TString numpart = record.sub(28,35); 
    int     nrata   = atoi(record.sub(35,37));
    int     num_rig = atoi(record.sub(10,13));
  
    TString dep (format("%2s%d%06ld%02d%2d%7s%02d", (const char*)"B1",3,nreg,nriga,anno,(const char*)numpart,nrata));         
  
    ttab.zero();
    ttab.put("CODTAB", dep);
  
    TRectype tabella (ttab.curr());
  
    for (ttab.read(_isgteq); !ttab.eof(); ttab.next())
    {
      if (ttab.curr() > tabella) break;

      buffer = (const char*) recf;    
      
      int b1nurt = atoi(buffer.sub(10,13));
      int tipo   = atoi(buffer.sub(37,38));
    
      if (b1nurt < num_rig && (tipo != 2 && tipo != 4))  
      {
        _esiste_pagsca = TRUE;  
        break;
      }
    }
  }   
  
  if (_esiste_pagsca)
    caso = 'r';
  
  TString codval = record.sub(79,82);
  codval.trim();
  real impv (record.sub(127,140));
  
  if (tipomov == 4)
  { 
    if (codval.empty() || (codval.not_empty() && impv != ZERO))
      caso = 'a';
    if (codval.not_empty() && impv == ZERO)
      caso = 'd';  
  }              
  _ttab->readat(rec);
  return caso;
}

void TTransfer_file::aggiorna_partita(TString& record,TString& tipo,real& importo,real& importoval,
                                      real& abbuoni,real& diffcam,real& ritenute)
{ 
  TRecnotype rec = _tpart->recno();
  TIsamtempfile& part = *_tpart;
  real    abb,diff;
  TString sez    = ""; 
  TString sezabb = "";  
  TString sezdc  = "";

  abb  = ZERO;
  diff = ZERO;
  
  part.setkey(1);
  part.zero();
  part.put(PART_TIPOCF,     tipo);
  part.put(PART_GRUPPO,     (atoi(record.sub(16,18))));
  part.put(PART_CONTO,      (atoi(record.sub(18,20))));
  part.put(PART_SOTTOCONTO, (atol(record.sub(20,26)))); 
  part.put(PART_ANNO,       _annoSCA);
  part.put(PART_NUMPART,    record.sub(28,35));
  part.put(PART_NRIGA,      _nrigaSC);
  if (part.read() == NOERR)
  { 
    sez      = part.get     (PART_SEZ);
    sezabb   = part.get     (PART_SEZABB);
    sezdc    = part.get     (PART_SEZDIFCAM);
    real imp = part.get_real(PART_IMPORTO) + importo;
    real val = part.get_real(PART_IMPORTOVAL) + importoval;
    
    part.put(PART_IMPORTO, imp);
    part.put(PART_IMPORTOVAL, val);

    real rit = part.get_real(PART_RITENUTE) + ritenute;
    part.put(PART_RITENUTE, rit);
    
    if (abbuoni != ZERO)
    {  
      if (sezabb.empty())  
      {
        abb = part.get_real(PART_ABBUONI) + abbuoni;
        sezabb = sez;
      }
      else
        if (sez == sezabb)
          abb = part.get_real(PART_ABBUONI) + abbuoni;        
        else
          abb = part.get_real(PART_ABBUONI) - abbuoni;                
      if (abb < ZERO)
      {
        abb = abb * -1;
        if (sezabb == "D")
          sezabb = "A";
        else          
          if (sezabb == "A")
          sezabb = "D";
      }            
      part.put(PART_SEZABB,  sezabb);   
      part.put(PART_ABBUONI, abb);  
    }
    
    if (diffcam != ZERO)
    {
      if (sezdc.empty())  
      {
        diff = part.get_real(PART_DIFFCAM) + diffcam;
        sezdc = sez;
      }
      else
        if (sez == sezdc)
          diff = part.get_real(PART_DIFFCAM) + diffcam;        
        else
          diff = part.get_real(PART_DIFFCAM) - diffcam;                
      if (diff < ZERO)
      {
        diff = diff * -1;
        if (sezdc == "D")
          sezdc = "A";
        else          
          if (sezdc == "A")
          sezdc = "D";      
      }                
      part.put(PART_SEZDIFCAM, sezdc);   
      part.put(PART_DIFFCAM,   diff);
    }
    part.rewrite();
  }         
  _tpart->readat(rec);
}


char TTransfer_file::leggi_sez_partita(TString& record,TString& tipo)
{ 
  TRecnotype rec = _tpart->recno();
  TIsamtempfile& part = *_tpart;
  
  char sez = '\0'; 
           
  part.setkey(1);
  part.zero();
  part.put(PART_TIPOCF,     tipo);
  part.put(PART_GRUPPO,     (atoi(record.sub(16,18))));
  part.put(PART_CONTO,      (atoi(record.sub(18,20))));
  part.put(PART_SOTTOCONTO, (atol(record.sub(20,26)))); 
  part.put(PART_ANNO,       _annoSCA);
  part.put(PART_NUMPART,    record.sub(28,35));
  part.put(PART_NRIGA,      _nrigaSC);
  if (part.read() == NOERR)
    sez = part.get_char(PART_SEZ);

  _tpart->readat(rec);
  
  return sez;
}

void TTransfer_file::pagsca(TString& record)
{                          
  TMappa_trc& trc  = mappa();
  TString     sigla,key;
  int         numfield = 200;     
  TString     tipoc;            
  real        importo,importoval,abbuoni,diffcam,ritenute,imp,impv;
  bool        solo_saldaconto = FALSE; 
  char        sez,sezione;  
  
  
  importo    = ZERO;
  importoval = ZERO;
  abbuoni    = ZERO;
  diffcam    = ZERO;
  ritenute   = ZERO;                            
  imp        = ZERO;
  impv       = ZERO;
  
  _esiste_pagsca = FALSE;                       
  
  int tipomov = atoi(record.sub(37,38));
  
  tipo_anagrafica(record,tipoc);
  
  int  num_scad = recupera_scadenze(record,tipoc);  
  if (num_scad == 0 || num_scad > 1)
  {
    _nrigaSCA = 9999;
    _nrataSCA = 9999;
  }  
  
  // Questa funzione ritorna: - 'p' nel caso di pagamento        
  //                          - 'r' nel caso di ritenuta
  //                          - 'a' nel caso di abbuono
  //                          - 'd' nel caso di differenza cambio
  char caso     = what_is_this(record,tipoc);  // I don't know
  
  sigla     = record.mid(0,2);
  key.format("%2s%d", (const char*)sigla,numfield);
    
  if (trc.is_key((const char *) key)) 
  {    
    _deppagsca->zero();

    do
    {
      int     from  = trc.from(key);
      int     to    = trc.to(key);
      TString fname = trc.field_name(key); 
      TString field = record.sub(from-1,to); 
      int     flag  = trc.flag(key);
      int     dec   = trc.flag_bis(key);
      
      if (fname != "IMP" && fname != "SEZ") 
      {
        TRecfield campo (*_deppagsca,fname);
        if (campo.type() == _realfld)
          negativo(field);
      }

      if (flag == 3)
      { 
        if (dec > 0)
          decimali(field,dec);

        real appoggio (field);    
      }

      if (fname == "TIPOC")
        field = tipoc;

      if (fname == "GRUPPO" || fname == "CONTO")
      {
        int app = atoi(field);
        field.format("%3d", app);
      }        
      if (fname == "SOTTOCONTO")
      {
        long sottoc = atol(field);
        field.format("%6ld", sottoc);
      }
      if (fname == "ANNO")
      {
        TString app  = field;
        int     anno = atoi(field);
        if (anno <= 25)
        {
          field = "20"; 
          field << app;
        }
        else 
        {
          field = "19";
          field << app; 
        }
      }
      if (fname == "NRIGA") 
      { 
        TString app (format("%4d", _nrigaSCA));
        field = app;        
      }
      if (fname == "NRATA")
      {
        TString nrata (format("%4d", _nrataSCA));
        field = nrata;        
        TString app (format("%4d", _nrigaSC));
        _deppagsca->put("NRIGP", app);
      }
      
      if (fname == "IMPORTO")
      {
        real appoggio (field);
        importo = appoggio; 
      }
      else 
        if (fname == "IMPORTOVAL")
        {
          real appoggio (field);
          importoval = appoggio;
        }
        else
        if (fname == "IMP")
        { 
          TString codval = record.sub(79,82);
          codval.trim();
        
          if (caso == 'a' || caso == 'd')
            _deppagsca->put(PAGSCA_ACCSAL, "S");
        else
          _deppagsca->put(PAGSCA_ACCSAL, "A");
          if (caso == 'p')
          {
            _deppagsca->put(PAGSCA_IMPORTO,    importo);
            _deppagsca->put(PAGSCA_IMPORTOVAL, importoval); 
            imp  = importo;
            impv = importoval;
          }    
          if (caso == 'a')
          {
            if (codval.empty())
              abbuoni = importo;
            else
              abbuoni = importoval; 
          }
          if (caso == 'd')
            diffcam = importo;
          if (caso == 'r')
          {
            ritenute = importo;
            _deppagsca->put(PAGSCA_RITENUTE, ritenute);
          }
                                                   
          sez = leggi_sez_partita(record,tipoc);
        
          if (abbuoni != ZERO)
          {
            if (sez != sezione)
              abbuoni = abbuoni * -1;  
            _deppagsca->put(PAGSCA_ABBUONI, abbuoni);  
          }                          
          if (diffcam != ZERO)
          {
            if (sez != sezione)
              diffcam = diffcam * -1;                
            _deppagsca->put(PAGSCA_DIFFCAM, diffcam);  
          }  
          if (_nrigaSCA == 9999 && _nrataSCA == 9999)
          {
            abbuoni = ZERO;
            diffcam = ZERO;
          }
//          aggiorna_partita(record,tipoc,imp,impv,abbuoni,diffcam,ritenute);        
        }
        else                                               
          if (fname == "SEZ")
          { 
            sezione = field[0];
            if (caso == 'a')
            {
              if (field == "A")
                _deppagsca->put(PAGSCA_PASSATT, "P");
              else
                if (field == "D")
                  _deppagsca->put(PAGSCA_PASSATT, "A");
            }
          }
          else
            if (flag == 2)
            {
              TString f = converti(field,FALSE);
              _deppagsca->put(fname,f);
            }
            else
              _deppagsca->put(fname, field);

      numfield++;
      key.format("%2s%d", (const char*) sigla,numfield);
    }
    while (trc.is_key((const char*) key));
  }  // if (trc.is_key((const char*) key)

  _tpagsca->setkey(1);
  _tpagsca->zero();
  _tpagsca->curr() = *_deppagsca;
  
  if (_tpagsca->read() == NOERR)     
  { 
    TString accsal = _tpagsca->get(PAGSCA_ACCSAL);
    real importo   = _tpagsca->get_real(PAGSCA_IMPORTO)    + _deppagsca->get_real(PAGSCA_IMPORTO);
    real valuta    = _tpagsca->get_real(PAGSCA_IMPORTOVAL) + _deppagsca->get_real(PAGSCA_IMPORTOVAL);
    real abbuoni   = _tpagsca->get_real(PAGSCA_ABBUONI)    + _deppagsca->get_real(PAGSCA_ABBUONI);
    real diffcam   = _tpagsca->get_real(PAGSCA_DIFFCAM)    + _deppagsca->get_real(PAGSCA_DIFFCAM);
    real ritenute  = _tpagsca->get_real(PAGSCA_RITENUTE)   + _deppagsca->get_real(PAGSCA_RITENUTE);

    if (accsal != "S")
      _tpagsca->put(PAGSCA_ACCSAL, _deppagsca->get(PAGSCA_ACCSAL));  
    if (caso == 'a')  
      _tpagsca->put(PAGSCA_PASSATT,    _deppagsca->get(PAGSCA_PASSATT));
    _tpagsca->put(PAGSCA_IMPORTO,    importo);
    _tpagsca->put(PAGSCA_IMPORTOVAL, valuta);
    _tpagsca->put(PAGSCA_ABBUONI,    abbuoni);
    _tpagsca->put(PAGSCA_DIFFCAM,    diffcam);
    _tpagsca->put(PAGSCA_RITENUTE,   ritenute);
    
    _tpagsca->rewrite();
  }
  else
  {
    _tpagsca->zero();
    _tpagsca->curr() = *_deppagsca;     
    _tpagsca->write();    
  }  
}

long TTransfer_file::determina_dimensione(FILE* f) 
{     
  CHECK(f, "Can't measure NULL file");
  fseek(f, 0, SEEK_END);
  const long s = ftell(f);
  fseek(f, 0, SEEK_SET);
  return s;
}

void TTransfer_file::new_key(TString& key, int tipo, TString& buffer)
{
  TString n_key = ""; 
  
  n_key << key.mid(0,2);
  if (tipo == 1)
    n_key << "1";
  else
    if (tipo == 2)
      n_key << "2";
    else
      if (tipo == 3 || tipo == 4 || tipo == 5 || tipo == 6)
        n_key << "3";
  n_key << key.mid(2,6);
  n_key << key.mid(8,2);
  n_key << buffer.mid(26,2); 
  n_key << buffer.mid(28,7); 
  n_key << buffer.mid(35,2);
  n_key << key.mid(10,3);
  
  key = n_key;      
}

//Trasforma un eventuale TRASFER composto da record con odinamento casuale
//in un file con record odinati in modo sequenziale
bool TTransfer_file::ordina_trasfer(const char* orig)
{ 
#if XVT_OS == XVT_OS_SCOUNIX
  const char* const rflag = "r";
#else
  const char* const rflag = "rb";
#endif

  open(orig);
  
  FILE* i = fopen(orig, rflag);
  if (!i) return error_box("Impossibile leggere il file %s", orig);
 
  long dim_t = determina_dimensione(i);  //Determina la dimensione del trasfer
  
  const word size = 256;
  TString buffer(size);
  
  int pos = 0;
  
  TString80 tmptab = "%";
  tmptab  << main_app().get_firm_dir();
  tmptab << "\\" << TEMP_TAB;
  _ttab = new TIsamtempfile(LF_TAB, tmptab, TRUE);
  
  long cicli = dim_t / size;  
  TProgind prog (cicli,"Ordinamento file TRASFER in corso\nPrego attendere",FALSE, TRUE, 1);    
  
  bool  ok = TRUE;          
    
  TRic_recfield recf (_ttab->curr(), "S0", 0, size);
    
  while (ok)
  {
    const word letti = fread((char*)(const char*)buffer, 1, size, i);
    buffer.cut(256);
    
    ok = (letti == size);
    if (!ok) break;
    
    prog.addstatus(1);
    
    TString key = buffer.mid(0,15);
    
    if (buffer.mid(0,2) == "B1")
    {               
      TString app;                            // Modifica del 06-09-96 relativa all'allineamento
      app = buffer.mid(28,7); 
      app.trim();                             // del numero di riferimento partita che per i file
      app.format("%-7s", (const char*) app);  // temporanei deve essere sempre a sinistra 
      buffer.overwrite(app,28);               // indipendentemente da quello che c'e' sul trasfer
    
      int tipomov = atoi(buffer.mid(37,1));
      new_key(key,tipomov,buffer);
    }  
      
    _ttab->put("CODTAB", key);
    
    recf = buffer;  
    
    int rc = _ttab->write();

#ifdef DBG  
  if (rc != NOERR) error_box("ERRORE. Per qualche motivo la write e' fallita!!! Errore n. %d",rc );
#endif
  }    
  
  fclose(i);       

  return ok;
}

//Scarica su file temp il contenuto del trasfer
bool TTransfer_file::fcopytemp(const char* orig, const char* dest)
{ 
  // conto i dischetti per l'apertura
  TString       sigle,nrec;
  long          nrec_cau,nrec_clifo,nrec_pcon,nrec_mov,nrec_moviva,nrec_salda;
  bool          is_delete = FALSE;

  const char* wflag;
#if XVT_OS == XVT_OS_SCOUNIX
  const char* const rflag = "r";
  wflag = "a";
#else
  const char* const rflag = "rb";
  wflag = "ab";
#endif
  
  ordina_trasfer(orig);
  
  // Legge numero di rec. del transfer (per la progind)                  
  _ttab->first();
  TRic_recfield recf (_ttab->curr(), "S0", 0, 256);
  TString rec = (const char*) recf;
  
  sigle = rec.sub(38,47); 
  nrec  = rec.sub(47,101);
  
  int pos = 0;
  
  if ( (pos = sigle.find('W')) >= 0)
  {
    _tmpcaus = "%";
    _tmpcaus << path();
    _tmpcaus << "\\" << TEMP_CAUS;
    _tmprcaus = "%";
    _tmprcaus << path();
    _tmprcaus << "\\" << TEMP_RCAUS;
    nrec_cau = atol(nrec.mid(pos*6,6));
  } 
  if ( (pos = sigle.find('A')) >= 0)
  {
    _tmpclifo = "%";
    _tmpclifo << path();
    _tmpclifo << "\\" << TEMP_CLIFO;
    nrec_clifo = atol(nrec.mid(pos*6,6));
  }
  if ( (pos = sigle.find('P')) >= 0)
  {
    _tmppcon = "%";
    _tmppcon << path();
    _tmppcon << "\\" << TEMP_PCON;   
    nrec_pcon = atol(nrec.mid(pos*6,6));
  }
  if ( (pos = sigle.find('Z')) >= 0)
  {
    _tmpmov = "%";
    _tmpmov  << path();
    _tmpmov << "\\" << TEMP_MOV;
    _tmprmov = "%";
    _tmprmov << path();         
    _tmprmov << "\\" << TEMP_RMOV;  
    nrec_mov = atol(nrec.mid(pos*6,6));
  }
  if ( (pos = sigle.find('U')) >= 0)
  { 
    is_delete = TRUE;
    
    _tmpmov = "%";
    _tmpmov  << path();
    _tmpmov << "\\" << TEMP_MOV; 
    _tmprmoviva = "%";
    _tmprmoviva <<  path();     
    _tmprmoviva << "\\" << TEMP_RMOVIVA;  
    nrec_moviva = atol(nrec.mid(pos*6,6));

    TString80 tmpocc = "%";
    tmpocc  << main_app().get_firm_dir();
    tmpocc << "\\" << TEMP_OCC;
    _toccas = new TIsamtempfile(LF_OCCAS, tmpocc, TRUE);
  }
  if ( (pos = sigle.find('B')) >= 0)
  {
    _tmppart = "%";
    _tmppart  << path();
    _tmppart << "\\" << TEMP_PART;
    _tpart   = new TIsamtempfile(LF_PARTITE, _tmppart, TRUE);
    _deppart = new TRectype(LF_PARTITE);
    _tmpscad  = "%";
    _tmpscad << path();         
    _tmpscad << "\\" << TEMP_SCAD;                         
    _tscad   = new TIsamtempfile(LF_SCADENZE, _tmpscad, TRUE);
    _depscad = new TRectype (LF_SCADENZE);
    _tmppagsca = "%";
    _tmppagsca  << path();
    _tmppagsca << "\\" << TEMP_PAGSCA;          
    _tpagsca   = new TIsamtempfile(LF_PAGSCA, _tmppagsca, TRUE);
    _deppagsca = new TRectype (LF_PAGSCA);
    nrec_salda = atol(nrec.mid(pos*6,6));
  }
   
  close();
  
  bool ok = TRUE;
   
  scrivi_header(dest,wflag);
  if (sigle.find('W') >= 0)
    scrivi_causali(nrec_cau);
  if (sigle.find('A') >= 0)    
    scrivi_clifo(nrec_clifo);
  if (sigle.find('P') >= 0)  
    scrivi_pcon(nrec_pcon);  
  if (sigle.find('Z') >= 0)  
    scrivi_PN(nrec_mov);     
  if (sigle.find('U') >= 0)  
    scrivi_IVA(nrec_moviva);
  if (sigle.find('B') >= 0)
    scrivi_SC(nrec_salda);
    
  if (is_delete) delete _toccas;
  
  delete _ttab;
  
  return ok;
}

void TTransfer_file::ordina_file_da_elaborare(TString& buffer)
{
  TString sigle_app  = "";
  TString numrec_app = "";
  int p;
  
  TString sigle  = buffer.sub(86,95);
  sigle.trim();
  TString numrec = buffer.sub(95,149);
  
  if ( (p = sigle.find('W')) >= 0)
  { 
    TString sigla = sigle.mid(p,1);
    TString num   = numrec.mid(p*6,6);
    sigle_app  << sigla;
    numrec_app << num;
  }
  if ( (p = sigle.find('A')) >= 0)
  {                  
    TString sigla = sigle.mid(p,1);
    TString num   = numrec.mid(p*6,6);
    sigle_app  << sigla;
    numrec_app << num;  
  }
  if ( (p = sigle.find('P')) >= 0)
  {   
    TString sigla = sigle.mid(p,1);
    TString num   = numrec.mid(p*6,6);
    sigle_app  << sigla;
    numrec_app << num;  
  }
  if ( (p = sigle.find('Z')) >= 0)
  {   
    TString sigla = sigle.mid(p,1);
    TString num   = numrec.mid(p*6,6);
    sigle_app  << sigla;
    numrec_app << num;  
  }
  if ( (p = sigle.find('U')) >= 0)
  {   
    TString sigla = sigle.mid(p,1);
    TString num   = numrec.mid(p*6,6);
    sigle_app  << sigla;
    numrec_app << num;  
  }
  if ( (p = sigle.find('B')) >= 0)
  {   
    TString sigla = sigle.mid(p,1);
    TString num   = numrec.mid(p*6,6);
    sigle_app  << sigla;
    numrec_app << num;  
  }                   
  buffer.overwrite(sigle_app,86);
  buffer.overwrite(numrec_app,95);
}

void TTransfer_file::scrivi_header(const char* dest, const char* wflag)
{
  const word size  = 256;
  const int  sizeH = 1024;
  TString buffer(sizeH);
  TString16 trec;
 
  FILE* o = fopen(dest, wflag);
  CHECKS(o, "Impossibile scrivere il file ", dest);

  TRic_recfield recf (_ttab->curr(), "S0", 0, 256);
  
  _ttab->zero();
  _ttab->put("CODTAB", " 1");
  _ttab->read();
  
  trec = (_ttab->get("CODTAB")).sub(0,2);
    
  if (trec == " 1")  // Copio il record di controllo nel file di appoggio
  {                  // header. 
    TString rec;
    rec = (const char*) recf;
    buffer.spaces();
    buffer.overwrite(rec,0);
    
    TString app;
    app.spaces(234); 
    TString app1;
    app1 = buffer.mid(0,101);
    TString str(45);
    str.spaces(45);
    app1.insert(str,15);
    app1.insert("0",70); 
    int pre = atoi(app1.sub(78,80));
    if (pre <= 25)
      app1.insert("20",78);
    else
      app1.insert("19",78);
    str = "";
//    str.format(85);
//    app.overwrite(str,149);
    ordina_file_da_elaborare(app1);
    app.overwrite(app1,0);
    buffer.overwrite(app,0);  
    buffer.cut(sizeH);
    fwrite((char*)(const char*)buffer, 1, sizeH, o);
    fclose(o);
  }
}

void TTransfer_file::scrivi_causali(long nrec)
{   
  const word size = 256;
  TString    buffer(size);
  TString16  trec;
  bool       create = TRUE;

  _prog = new TProgind (nrec,"Trasferimento Tabella Causali in corso\nPrego attendere",FALSE, TRUE, 1); 
    
  TRic_recfield recf (_ttab->curr(), "S0", 0, 256);
    
  _ttab->zero();
  _ttab->put("CODTAB", "W1");
  for (_ttab->read(); !_ttab->eof(); _ttab->next())
  {
    trec = (_ttab->get("CODTAB")).sub(0,2);
    
    if (trec != "W1") break;
  
    buffer = (const char*) recf;
      
    write_tmp_tabelle(buffer,create);
    create = FALSE;
  }                         
  delete _prog;
}

void TTransfer_file::scrivi_clifo(long nrec)
{            
  const word size = 256;
  TString    buffer(size);
  TString16  trec;
  bool       create = TRUE;

  _prog = new TProgind (nrec,"Trasferimento Anagrafica Clienti/Fornitori in corso\nPrego attendere",FALSE, TRUE, 1); 
    
  TRic_recfield recf (_ttab->curr(), "S0", 0, 256);
    
  _ttab->zero();
  _ttab->put("CODTAB", "A1");
  for (_ttab->read(); !_ttab->eof(); _ttab->next())
  {
    trec = (_ttab->get("CODTAB")).sub(0,2);
    
    if (trec != "A1") break;
    
    buffer = (const char*) recf;
        
    write_tmp_tabelle(buffer,create);
    create = FALSE;
  }                         
  delete _prog;
}

void TTransfer_file::scrivi_pcon(long nrec)
{            
  const word size = 256;
  TString    buffer(size);
  TString16  trec;
  bool       create = TRUE;

  _prog = new TProgind (nrec,"Trasferimento Anagrafica Piano dei Conti in corso\nPrego attendere",FALSE, TRUE, 1);  
  
  TRic_recfield recf (_ttab->curr(), "S0", 0, 256);
    
  _ttab->zero();
  _ttab->put("CODTAB", "P1");
  for (_ttab->read(); !_ttab->eof(); _ttab->next())
  {
    trec = (_ttab->get("CODTAB")).sub(0,2);
    
    if (trec[0] != 'P') break;
    
    buffer = (const char*) recf;
        
    write_tmp_tabelle(buffer,create);
    create = FALSE;
  }                         
  delete _prog;
}

void TTransfer_file::scrivi_PN(long nrec)
{            
  const word size = 256;
  TString    buffer(size);
  TString16  trec;
  bool       create = TRUE;

  _prog = new TProgind (nrec,"Trasferimento Movimenti di Prima nota in corso\nPrego attendere",FALSE, TRUE, 1); 
      
  TRic_recfield recf (_ttab->curr(), "S0", 0, 256);
    
  _ttab->zero();
  _ttab->put("CODTAB", "Z1");
  for (_ttab->read(); !_ttab->eof(); _ttab->next())
  {
    trec = (_ttab->get("CODTAB")).sub(0,2);
    
    if (trec != "Z1") break;
    
    buffer = (const char*) recf;
        
    write_tmp_movPN(buffer,create);
    create = FALSE;
  }                         
  delete _prog;
}

void TTransfer_file::scrivi_IVA(long nrec)
{            
  const word size = 256;
  TString    buffer(size);
  TString16  trec;
  bool       create = TRUE;

  _prog = new TProgind (nrec,"Trasferimento Movimenti Iva in corso\nPrego attendere",FALSE, TRUE, 1); 
      
  TRic_recfield recf (_ttab->curr(), "S0", 0, 256);
    
  _ttab->zero();
  _ttab->put("CODTAB", "U1");
  for (_ttab->read(); !_ttab->eof(); _ttab->next())
  {
    trec = (_ttab->get("CODTAB")).sub(0,2);
    
    if (trec != "U1") break;
    
    buffer = (const char*) recf;
        
    write_tmp_movIVA(buffer,create);
    create = FALSE;
  }                         
  delete _prog;
}

void TTransfer_file::scrivi_SC(long nrec)
{            
  const word size = 256;
  TString    buffer(size);
  TString16  trec;
  bool       create = TRUE;
  
  _nregSC_p    = -1;
  _numrigSC_p  = -1;
  _annoSC_p    = -1;
  _numpartSC_p = "-1";
  
  _prog = new TProgind (nrec,"Trasferimento Movimenti saldaconto in corso\nPrego attendere",FALSE, TRUE, 1); 
      
  TRic_recfield recf (_ttab->curr(), "S0", 0, 256);
    
  _ttab->zero();
  _ttab->put("CODTAB", "B1");
  for (_ttab->read(); !_ttab->eof(); _ttab->next())
  {
    trec = (_ttab->get("CODTAB")).sub(0,2);
    
    if (trec != "B1") break;
    
    buffer = (const char*) recf;
        
    write_tmp_movSC(buffer,create);
    create = FALSE;
  }                         
  delete _prog;
  delete _tpart;
  delete _deppart;
  delete _tscad;   
  delete _depscad;
  delete _tpagsca; 
  delete _deppagsca;
}
                    
//Scarica su file temp il contenuto del trasfer
bool TTransfer_file::fcopytemp_PC(const char* orig, const char* dest)
{ 
  // conto i dischetti per l'apertura
  TString       sigle;
  bool          is_delete = FALSE;

  const char* wflag;
#if XVT_OS == XVT_OS_SCOUNIX
  const char* const rflag = "r";
  wflag = "a";
#else
  const char* const rflag = "rb";
  wflag = "ab";
#endif

  // Legge numero di rec. del trasfer (per la progind)                  
  open(orig);
  if (read_control_rec())
    sigle = sigle_file(); 
  
  FILE* i = fopen(orig, rflag);
  if (!i) return error_box("Impossibile leggere il file %s", orig);

  FILE* o = fopen(dest, wflag);
  CHECKS(o, "Impossibile scrivere il file ", dest);
  
  const word size = 1024;
  TString buffer(size);
  TString16 trec;
  
  if (sigle.find('W') >= 0)
  {
    _tmpcaus = "%";
    _tmpcaus << path();
    _tmpcaus << "\\" << TEMP_CAUS;
    _tmprcaus = "%";
    _tmprcaus << path();
    _tmprcaus << "\\" << TEMP_RCAUS;
    _tcaus    = new TIsamtempfile(LF_CAUSALI, _tmpcaus, TRUE);
    _depcaus  = new TRectype (LF_CAUSALI);    
    _trcaus   = new TIsamtempfile(LF_RCAUSALI, _tmprcaus, TRUE);
    _deprcaus = new TRectype (LF_RCAUSALI);    
  } 
  if (sigle.find('A') >= 0)
  {
    _tmpclifo = "%";
    _tmpclifo << path();
    _tmpclifo << "\\" << TEMP_CLIFO;      
    _tclifo   = new TIsamtempfile(LF_CLIFO, _tmpclifo, TRUE);
    _depclifo = new TRectype (LF_CLIFO);    
  }
  if (sigle.find('P') >= 0)
  {
    _tmppcon = "%";
    _tmppcon << path();
    _tmppcon << "\\" << TEMP_PCON;      
    _tpcon   = new TIsamtempfile(LF_PCON, _tmppcon, TRUE);
    _deppcon = new TRectype (LF_PCON);        
  }
  if (sigle.find('Z') >= 0)
  {
    _tmpmov = "%";
    _tmpmov  << path();
    _tmpmov << "\\" << TEMP_MOV;
    _tmprmov = "%";
    _tmprmov << path();         
    _tmprmov << "\\" << TEMP_RMOV;  
    _tmov    = new TIsamtempfile(LF_MOV, _tmpmov, TRUE);
    _depmov  = new TRectype (LF_MOV);        
    _trmov   = new TIsamtempfile(LF_RMOV, _tmprmov, TRUE);
    _deprmov = new TRectype (LF_RMOV);    

    TString80 tmpocc = "%";
    tmpocc  << main_app().get_firm_dir();
    tmpocc << "\\" << TEMP_OCC;
    _toccas   = new TIsamtempfile(LF_OCCAS, tmpocc, TRUE);
    _depoccas = new TRectype (LF_OCCAS);    
  }
  if (sigle.find('U') >= 0)
  { 
    is_delete = TRUE;
    
    _tmpmov = "%";
    _tmpmov  << path();
    _tmpmov << "\\" << TEMP_MOV; 
    _tmprmoviva = "%";
    _tmprmoviva <<  path();     
    _tmprmoviva << "\\" << TEMP_RMOVIVA;  
    _triva   = new TIsamtempfile(LF_RMOVIVA, _tmprmoviva, TRUE);
    _depriva = new TRectype (LF_RMOVIVA);    
  }
  if (sigle.find('B') >= 0)
  {
    _tmppart = "%";
    _tmppart  << path();
    _tmppart << "\\" << TEMP_PART;
    _tmpscad = "%";
    _tmpscad << path();         
    _tmpscad << "\\" << TEMP_SCAD;  
    _tmppagsca = "%";
    _tmppagsca  << path();
    _tmppagsca << "\\" << TEMP_PAGSCA; 

    _tpart     = new TIsamtempfile(LF_PARTITE, _tmppart, TRUE);
    _deppart   = new TRectype (LF_PARTITE);        
    _tscad     = new TIsamtempfile(LF_SCADENZE, _tmpscad, TRUE);
    _depscad   = new TRectype (LF_SCADENZE);    
    _tpagsca   = new TIsamtempfile(LF_PAGSCA, _tmppagsca, TRUE);
    _deppagsca = new TRectype (LF_PAGSCA);    
  }
   
  close();
   
  bool  ok          = TRUE;          
  bool  prima_volta = TRUE;
  
  long dim_t = determina_dimensione(i);  //Determina la dimensione del trasfer
  long cicli = dim_t / size;
  _prog = new TProgind (cicli,"Elaborazione file TRASFER in corso\nPrego attendere",FALSE, TRUE, 1);   
  
  while (ok)
  {
    const word letti = fread((char*)(const char*)buffer, 1, size, i);

    trec = buffer.sub(0,2);
    
    if (trec == " 1")  // Copio il record di controllo nel file di appoggio
    {                  // header.
      ordina_file_da_elaborare(buffer);    
      ok = fwrite((char*)(const char*)buffer, 1, letti, o) == letti;
      fclose(o);
    }
    
    if (trec == "B1" || trec == "B2" || trec == "B3")
    {
      TString app = buffer.mid(19,7);   
      app.trim();                            // Modifica del 06-09-96 relativa all'allineamento
      app.format("%-7s", (const char*) app); // del numero di riferimento partita che per i file
      buffer.overwrite(app,19);              // temporanei deve essere sempre a sinistra
    }                                        // indipendentemente da quello che c'e' sul trasfer
      
    if (trec == "W1")
      write_testata_causali(buffer);
    
    if (trec == "W2")
      write_righe_causali(buffer);
      
    if (trec == "A1")                              // Clienti e Fornitori
      write_clienti_fornitori(buffer);

    if (trec == "P1" || trec == "P2" || trec == "P3")  // Piano dei conti
      write_piano_conti(buffer);

    if (trec == "Z1")                  
      write_testata_movimenti(buffer);
    
    if (trec == "Z2")
      write_righe_contabili(buffer);
      
    if (trec == "U1")    
      write_righe_IVA(buffer);
    
    if (trec == "B1")
      write_partite(buffer);
      
    if (trec == "B2")
      write_scadenze(buffer);
      
    if (trec == "B3")
      write_pagsca(buffer);
          
    ok = (letti == size);
  }    
  
  fclose(i);
  
  delete _prog;

  if (sigle.find('W') >= 0)
  {
    delete _tcaus;
    delete _depcaus;
    delete _trcaus;
    delete _deprcaus;
  } 
  if (sigle.find('A') >= 0)
  {
    delete _tclifo;
    delete _depclifo;
  }
  if (sigle.find('P') >= 0)
  {
    delete _tpcon;
    delete _deppcon;
  }
  if (sigle.find('Z') >= 0)
  {
    delete _tmov;
    delete _depmov;
    delete _trmov;
    delete _deprmov;
  }
  if (sigle.find('U') >= 0)
  { 
    delete _triva;
    delete _depriva;
  }
  if (sigle.find('B') >= 0)
  {
    delete _tpart;
    delete _deppart;
    delete _tscad;
    delete _depscad;
    delete _tpagsca;
    delete _deppagsca;
  }
  if (is_delete)
  {
    delete _toccas;
    delete _depoccas;
  }
  
  return ok;
}

void TTransfer_file::write_testata_causali(TString& record)
{ 
  TString       sigla,key,str;
  int           numfield = 1;  
  TMappa_trc&   trc  = mappa();
  
  sigla     = record.mid(0,2);
  key.format("%2s%d", (const char*)sigla,numfield);
           
  _depcaus->zero();  
             
  if (trc.is_key((const char *) key)) 
  {    
    do
    {  
      int     from  = trc.from(key);
      int     to    = trc.to(key);
      TString fname = trc.field_name(key); 
      int     flag  = trc.flag(key);
      TString field = record.sub(from-1,to); 
      
      if (fname == CAU_TIPOMOV)
        if (field == "0")
          field = "";
            
      _depcaus->put(fname, (const char*)field);                      

      numfield++;
      key.format("%2s%d", (const char*) sigla,numfield);
    }
    while (trc.is_key((const char*) key));
  } 

  _tcaus->zero();
  _tcaus->curr() = *_depcaus;
      
  if (_tcaus->read() == NOERR)     
  {   
    _tcaus->zero();
    _tcaus->curr() = *_depcaus;
    _tcaus->rewrite();
  }
  else
  {
    _tcaus->zero();
    _tcaus->curr() = *_depcaus;     
    _tcaus->write();    
  } 
        
  _prog->addstatus(1);
}

void TTransfer_file::write_righe_causali(TString& record)
{ 
  TString       sigla,key,str;
  int           numfield = 1;  
  TMappa_trc&   trc  = mappa();
  
  sigla     = record.mid(0,2);
  key.format("%2s%d", (const char*)sigla,numfield);

  _deprcaus->zero();  
    
  if (trc.is_key((const char *) key)) 
  {    
    do
    {  
      int     from  = trc.from(key);
      int     to    = trc.to(key);
      TString fname = trc.field_name(key); 
      int     flag  = trc.flag(key);
      TString field = record.sub(from-1,to); 
      
      if (fname == RCA_NRIGA)
      {
        int nriga = atoi(field);  
        field.format("%3d", nriga);
      }
      if (fname == RCA_GRUPPO || fname == RCA_CONTO) 
      {
        int  gruppo,conto;
        char tipo;
          
        if (fname == RCA_GRUPPO) 
        {
          gruppo = atoi(field);  
          field.format("%3d", gruppo);
        }
        if (fname == RCA_CONTO) 
        {
          conto = atoi(field);
          field.format("%3d", conto);
          tipo = TipoConto(gruppo,conto);
          _deprcaus->put(RCA_TIPOCF, tipo);          
        }            
      }
      if (fname == RCA_SOTTOCONTO)
      {
        long sottoc = atol(field);
        field.format("%6ld", sottoc);
      }
        
      _deprcaus->put(fname, (const char*)field);                      

      numfield++;
      key.format("%2s%d", (const char*) sigla,numfield);
    }
    while (trc.is_key((const char*) key));
  } 

  _trcaus->zero();
  _trcaus->curr() = *_deprcaus;
      
  if (_trcaus->read() == NOERR)     
  {   
    _trcaus->zero();
    _trcaus->curr() = *_deprcaus;
    _trcaus->rewrite();
  }
  else
  {
    _trcaus->zero();
    _trcaus->curr() = *_deprcaus;     
    _trcaus->write();    
  }      
  
  _prog->addstatus(1);
}

void TTransfer_file::write_clienti_fornitori(TString& record)
{ 
  TString sigla,key,com,comune,cap;
  int     numfield = 1;  
  bool    is_foreign=FALSE;
  TMappa_trc&       trc  = mappa();
  
  sigla     = record.mid(0,2);
  key.format("%2s%d", (const char*)sigla,numfield);

  _depclifo->zero();  
  
  if (trc.is_key((const char *) key)) 
  {    
    do
    {
      int     from  = trc.from(key);
      int     to    = trc.to(key);
      TString fname = trc.field_name(key); 
      int     flag  = trc.flag(key);
      TString field = record.sub(from-1,to); 
        
      if (fname == CLI_CODCF)
      {
        long codcf = atol(field);
        field.format("%6ld", codcf);
      }
      if (fname == CLI_ALLEG)
        if (field == "2") 
          _depclifo->put(CLI_OCCAS, (const char*) "X");                      
        else
          if (field == "5") is_foreign = TRUE;
      
      if (fname == CLI_CODALLEG)
      {
        long codalleg = atol(field); 
        field.format("%6ld", codalleg);
      }                                
      if (fname == CLI_GRUPPO || fname == CLI_GRUPPORIC)
      {
        int gruppo = atoi(field);
        field.format("%3d", gruppo);
      }
      if (fname == CLI_CONTO || fname == CLI_CONTORIC)
      {  
        int conto = atoi(field);
        field.format("%3d", conto);
      }
      if (fname == CLI_SOTTOCRIC)
      {
        long sottoc = atol(field);
        field.format("%6ld", sottoc);
      }                           
      if (fname == CLI_COMCF)  
      {
        com = field;  
        com.trim();
      } 
      if (fname == CLI_CAPCF)  
      { 
        field.trim();
        if (field == "00000")
          cap = "";
        else
          cap = field;      
      }
      if (fname == CLI_LOCCF)
      {
        comune = "";
        
        if (com.empty() && !is_foreign)
        {    
          if (cap.not_empty())
            comune = cerca_comune_cap(cap,field);
          if (comune.empty())
            comune = cerca_comune_den(field);
          if (comune.not_empty())
            _depclifo->put(CLI_COMCF, comune);
        }
      } 
      
      if (flag == 2)
      {
        TString f = converti(field,TRUE);
        _depclifo->put(fname,f);      
      }
      else  
        _depclifo->put(fname, (const char*)field);                      

      numfield++;
      key.format("%2s%d", (const char*) sigla,numfield);
    }
    while (trc.is_key((const char*) key));
  } 

  _tclifo->zero();
  _tclifo->curr() = *_depclifo;
      
  if (_tclifo->read() == NOERR)     
  {   
    _tclifo->zero();
    _tclifo->curr() = *_depclifo;
    _tclifo->rewrite();
  }
  else
  {
    _tclifo->zero();
    _tclifo->curr() = *_depclifo;     
    _tclifo->write();    
  }
  
  _prog->addstatus(1);
}

void TTransfer_file::write_piano_conti(TString& record)
{ 
  TString sigla,key;
  int     numfield = 1;  
  TMappa_trc&       trc  = mappa();
  
  sigla     = record.mid(0,2);
  key.format("%2s%d", (const char*)sigla,numfield);

  _deppcon->zero();
    
  if (trc.is_key((const char *) key)) 
  {    
    do
    {  
      int     from  = trc.from(key);
      int     to    = trc.to(key);
      TString fname = trc.field_name(key); 
      int     flag  = trc.flag(key);
      TString field = record.sub(from-1,to); 
        
      //Quando ricevo la IV direttiva del piano dei conti per evitare che nell'archivio,
      //in caso di numero romano vuoto, venga memorizzato la stringa letta sul trasfer ("000"),
      //vuoto la stringa prima di fare la put.
      if (fname == PCN_GRUPPO)
      {
        int gruppo = atoi(field);
        field.format("%3d", gruppo);
      }                             
      if (fname == PCN_CONTO) 
      {
        int conto = atoi(field);
        field.format("%3d", conto);
      }                            
      if (fname == PCN_SOTTOCONTO)
      {
        long sottoc = atol(field);
        field.format("%6ld", sottoc);
      }
      if (fname == PCN_SEZIVD || fname == PCN_SEZIVDOPP)
        if (field == " ")
          field = "0";
      
      _deppcon->put(fname, (const char*)field);                      

      numfield++;
      key.format("%2s%d", (const char*) sigla,numfield);
    }
    while (trc.is_key((const char*) key));
  }

  _tpcon->zero();
  _tpcon->curr() = *_deppcon;
      
  if (_tpcon->read() == NOERR)     
  {   
    _tpcon->zero();
    _tpcon->curr() = *_deppcon;
    _tpcon->rewrite();
  }
  else
  {
    _tpcon->zero();
    _tpcon->curr() = *_deppcon;     
    _tpcon->write();    
  }
  
  _prog->addstatus(1);  
}

int TTransfer_file::annoes_PC(TString& data)
{ 
  TTable esc ("ESC");
  int anno = 0;
  
  TDate datacomp (data);
  int ae = datacomp.year();
  TString dep = format("%04d", ae);
  esc.zero();
  esc.put("CODTAB", dep);
  if (esc.read() == NOERR)
    anno = ae;
    
  return anno;
}

void TTransfer_file::causale(TString& cau,TString& tipo,TString& descr)
{
  TLocalisamfile caus (LF_CAUSALI);
  
  caus.setkey(1);
  caus.zero();
  caus.put(CAU_CODCAUS, cau);
  if (caus.read() == NOERR)
  {
    descr = caus.get(CAU_DESCR);
    tipo  = caus.get(CAU_TIPODOC);
  }
  else
  {
    descr = "";
    tipo  = "";
  }
}

int TTransfer_file::registro(TString& reg,int anno)
{
  TTable  rg ("REG");
  TString dep;
  int     tipo = 0;
  
  dep.format("%04d%s", anno, (const char*) reg);
  
  rg.zero();  
  rg.put("CODTAB", dep);
  if (rg.read() == NOERR)
    tipo = rg.get_int("I0");
    
  return tipo;
}

void TTransfer_file::write_testata_movimenti(TString& record)
{ 
  TString      sigla,key,descr;
  int          numfield = 1;   
  TMappa_trc&  trc  = mappa();
  int          annoiva;
  bool         registra_occas = FALSE;
  bool         occas          = TRUE;
  
  sigla     = record.mid(0,2);
  key.format("%2s%d", (const char*)sigla,numfield);

  _depmov->zero();    
      
  if (trc.is_key((const char *) key)) 
  {    
    _numreg = atol(record.sub(2,9));

    do
    {  
      int     from  = trc.from(key);
      int     to    = trc.to(key);
      TString fname = trc.field_name(key); 
      TString field = record.sub(from-1,to); 
      int     flag  = trc.flag(key);
      int     dec   = trc.flag_bis(key);
      
      if (flag != 4)  //Xche' sono i campi degli occasionali e gli da fastidio costruire un
      {               //recfield con _depmov e un campo degli occasionali
        TRecfield campo (*_depmov,fname);
        if (campo.type() == _realfld)
        { 
          TString sign,importo;
                    
          importo = field;            
          strip_zero(importo);
          if (importo.not_empty())
          {
            if (fname == MOV_TOTDOC)
            {
              sign  = record.sub(180,181); 
              if (sign == "-")
                field = sign << importo;
              else
                field = importo;
            }                         
            if (fname == MOV_RITFIS)
            {
              sign  = record.sub(195,196);
              if (sign == "-")
                field = sign << importo;        
              else
                field = importo;
            }
            if (fname == MOV_RITSOC)
            {
              sign  = record.sub(210,211);
              if (sign == "-")
                field = sign << importo;        
              else 
                field = importo;
            }
            if (fname == MOV_CORRLIRE)
            {
              sign  = record.sub(242,243);
              if (sign == "-")
                field = sign << importo;        
              else
                field == importo;
            }
            if (fname == MOV_CORRVALUTA)
            {
              sign  = record.sub(257,258);
              if (sign == "-")
                field = sign << importo;        
              else 
                field = importo;
            }
          }
          else
            field = importo;  
        }  
      }
      
      if (fname == MOV_NUMREG)
      {
        long numreg = atol(field);
        field.format("%7ld", numreg);        
      }
      
      if (flag == 3)
      { 
        if (dec > 0)
          decimali(field,dec);
            
        real appoggio (field);
        field = appoggio.string();
      }

      if (fname == MOV_DESCR)
      {     
        field.trim();
        if (field.empty() && _scelta == 'S')
          field = descr;
      }

      if (fname == MOV_REG)
      {
        int tipo = registro (field,annoiva);
        if (tipo == 1)
          _depmov->put(MOV_TIPO, "C");
        else
          if (tipo == 2)
            _depmov->put(MOV_TIPO, "F");
      }
      
      if (fname == MOV_OCFPI)
        if (field.trim().empty())  
        {
          TString rags = record.sub(290,340);
          if (rags.trim().not_empty())
          {
            TString app = "RIC";
            _npoccas++;
            field.format("%3s%13ld", (const char*)app,_npoccas);  
          }
          else
            occas = FALSE;         
        }
          
      if (flag == 2)
      {
        TString f = converti(field,TRUE);
        _depmov->put(fname,f);

        if (fname == MOV_DATACOMP)
        {
          _annoes = annoes_PC(f);
          _depmov->put(MOV_ANNOES, _annoes);
        }                                

        if (fname == MOV_DATAREG)
        {     
          TDate datareg (f);
          annoiva = datareg.year();
          _depmov->put(MOV_ANNOIVA,  annoiva);
        }
      }
      else
        if (fname == MOV_CODCAUS)
        {
          TString tipodoc;     
          
          causale(field,tipodoc,descr);
          _depmov->put(MOV_CODCAUS, field);
          _depmov->put(MOV_TIPODOC, tipodoc);
        }
        else
          if (flag == 4 || fname == MOV_OCFPI)
          { 
            if (occas)
            {
              if (!registra_occas)
                _depoccas->zero(); 
              if (fname == "DNASC")
              {
                TString f = converti(field,TRUE);
                field = f;
              }
              if (fname == "OCFPI") 
              {
                _depmov->put(fname,field);
                _depoccas->put("CFPI", field);
              }
              else
                if (fname == "COM")
                {
                  field.trim();
                  if (field.empty())
                  {
                    TString denominazione = record.sub(403,453);
                    denominazione.trim();
                    TString comune (cerca_comune_den(denominazione));
                    _depoccas->put("COM", comune);
                  }                
                  else
                    _depoccas->put("COM", field);
                }  
                else
                  if (fname == "COMNASC")
                  {
                    field.trim();
                    if (field.empty())
                    {
                      TString denominazione = record.sub(473,523);
                      denominazione.trim();
                      TString comune (cerca_comune_den(denominazione));
                      _depoccas->put("COMNASC", comune);
                    }                
                    else
                      _depoccas->put("COMNASC", field);
                  }  
                  else 
                    _depoccas->put(fname, field);
              registra_occas = TRUE;
            }
          }
          else
            _depmov->put(fname, field);
          
      numfield++;
      key.format("%2s%d", (const char*) sigla,numfield);
    }
    while (trc.is_key((const char*) key));    
  }

  _tmov->zero();
  _tmov->curr() = *_depmov;
      
  if (_tmov->read() == NOERR)     
  {   
    _tmov->zero();
    _tmov->curr() = *_depmov;
    _tmov->rewrite();
  }
  else
  {
    _tmov->zero();
    _tmov->curr() = *_depmov;     
    _tmov->write();    
  }
  
  if (registra_occas)
  {                        
    _toccas->zero();
    _toccas->curr() = *_depoccas;
      
    if (_toccas->read() == NOERR)     
    {   
      _toccas->zero();
      _toccas->curr() = *_depoccas;
      _toccas->rewrite();
    }
    else
    {
      _toccas->zero();
      _toccas->curr() = *_depoccas;     
      _toccas->write();    
    }
    registra_occas = FALSE;
  }                 
  _prog->addstatus(1);  
}

void TTransfer_file::write_righe_contabili(TString& record)
{ 
  TString     sigla,key;
  int         numfield = 1;  
  TMappa_trc& trc  = mappa();
  char        tipo = '\0';
  real        importo = ZERO;
  int         gruppo;
  
  sigla     = record.mid(0,2);
  key.format("%2s%d", (const char*)sigla,numfield);

  _deprmov->zero();
      
  if (trc.is_key((const char *) key)) 
  {    
    do
    {  
      int     from  = trc.from(key);
      int     to    = trc.to(key);
      TString fname = trc.field_name(key); 
      TString field = record.sub(from-1,to); 
      int     flag  = trc.flag(key);
      int     dec   = trc.flag_bis(key);
          
      TRecfield campo (*_deprmov,fname);
      if (campo.type() == _realfld)
      { 
        TString sign,importo;
                    
        importo = field;            
        strip_zero(importo);
        if (importo.not_empty())
        {
          if (fname == RMV_IMPORTO)
          {
            sign  = record.sub(143,144);
            if (sign == "-")
              field = sign << importo;
            else
              field = importo;
          }                         
        }
        else
          field = importo;
      }  

      if (flag == 3)
      { 
        if (dec > 0)
          decimali(field,dec);
            
        real appoggio (field);
        field = appoggio.string();
      }
            
      if (fname == RMV_IMPORTO)
      {
        real imp = real::ita2eng(field);  
        importo = imp;
      }  
      
      if (fname == RMV_NUMRIG)
      {
        int nriga = atoi(field);
        field.format("%3d", nriga);
      }                            
      if (fname == RMV_GRUPPO || fname == RMV_GRUPPOC)
      {
        gruppo = atoi(field);
        field.format("%3d", gruppo);
      }        
      if (fname == RMV_CONTO || fname == RMV_CONTOC)
      {
        int conto = atoi(field);
        field.format("%3d", conto);
        tipo = TipoConto(gruppo,conto);
        if (fname == RMV_CONTO)
          _deprmov->put(RMV_TIPOC, tipo);
        if (fname == RMV_CONTOC)
          _deprmov->put(RMV_TIPOCC, tipo);
      }                            
      if (fname == RMV_SOTTOCONTO || fname == RMV_SOTTOCONTOC)
      {
        long sottoc = atol(field);
        field.format("%6ld", sottoc);
      }

      if (flag == 2)
      {
        TString f = converti(field,TRUE);
        _deprmov->put(fname,f);
      }
      else  
        if (fname == RMV_NUMREG)
        {                                 
          long nreg = atol(field);
          field.format("%7ld", nreg);
          _deprmov->put(RMV_ANNOES,  _annoes);                                     
          _deprmov->put(RMV_NUMREG,  field);
        }
        else
          _deprmov->put(fname, field);
          
      numfield++;
      key.format("%2s%d", (const char*) sigla,numfield);
    }
    while (trc.is_key((const char*) key));
  }     

  _trmov->zero();
  _trmov->curr() = *_deprmov;
      
  if (_trmov->read() == NOERR)     
  {   
    _trmov->zero();
    _trmov->curr() = *_deprmov;
    _trmov->rewrite();
  }
  else
  {
    _trmov->zero();
    _trmov->curr() = *_deprmov;     
    _trmov->write();    
  }                                       
  _prog->addstatus(1);  
}

void TTransfer_file::write_righe_IVA(TString& record)
{ 
  TString     sigla,key;
  int         numfield = 1;   
  TMappa_trc& trc  = mappa();
  int         gruppo;
  
  sigla     = record.mid(0,2);
  key.format("%2s%d", (const char*)sigla,numfield);

  _depriva->zero();
      
  if (trc.is_key((const char *) key)) 
  {
    do
    {  
      int     from  = trc.from(key);
      int     to    = trc.to(key);
      TString fname = trc.field_name(key); 
      TString field = record.sub(from-1,to); 
      int     flag  = trc.flag(key);
      int     dec   = trc.flag_bis(key);
          
      TRecfield campo (*_depriva,fname);
      if (campo.type() == _realfld)
      { 
        TString sign,importo;
                    
        importo = field;            
        strip_zero(importo);
        if (importo.not_empty())
        {
          if (fname == RMI_IMPONIBILE)
          {
            sign  = record.sub(64,65);
            if (sign == "-")
              field = sign << importo;
            else
              field = importo;
          }
          if (fname == RMI_IMPOSTA)
          {
            sign  = record.sub(79,80);
            if (sign == "-")
              field = sign << importo;
            else
              field = importo;
          }
        }
        else
          field = importo;                                 
      }  
                                                     
      if (flag == 3)
      {
        if (dec > 0)
          decimali(field,dec);

        real appoggio (field);
        field = appoggio.string();  
      }                           
      if (fname == RMI_NUMRIG)
      {
        int nriga = atoi(field);
        field.format("%3d", nriga);
      }  
      if (fname == RMI_GRUPPO)
      {
        gruppo = atoi(field);
        field.format("%3d", gruppo);
      }  
      if (fname == RMI_CONTO)
      {
        int conto = atoi(field);
        field.format("%3d", conto);
        char tipo = TipoConto(gruppo,conto);
        _depriva->put(RMI_TIPOC, tipo);
      }
      if (fname == RMI_SOTTOCONTO)
      {
        long sottoc = atoi(field);
        field.format("%6ld", sottoc);
      }  
      if (fname == RMI_TIPODET || fname == RMI_TIPOCR || fname == RMI_TIPOATT)
       if (field == "0")
         field = "";
         
      if (fname == RMI_NUMREG)
      {                               
        long nreg = atol(field);
        field.format("%7ld", nreg);
        _depriva->put(RMI_ANNOES,   _annoes);                                     
        _depriva->put(RMI_NUMREG,   field);
      }
      else
        _depriva->put(fname, field);          
      
      numfield++;
      key.format("%2s%d", (const char*) sigla,numfield);
    }
    while (trc.is_key((const char*) key));
  }

  _triva->zero();
  _triva->curr() = *_depriva;
      
  if (_triva->read() == NOERR)     
  {   
    _triva->zero();
    _triva->curr() = *_depriva;
    _triva->rewrite();
  }
  else
  {
    _triva->zero();
    _triva->curr() = *_depriva;     
    _triva->write();    
  }
  _prog->addstatus(1);                                    
}

void TTransfer_file::write_partite(TString& record)
{ 
  TString      sigla,key;
  int          numfield = 1;   
  TMappa_trc&  trc  = mappa();
  
  sigla     = record.mid(0,2);
  key.format("%2s%d", (const char*)sigla,numfield);

  _deppart->zero();    
      
  if (trc.is_key((const char *) key)) 
  {    
    do
    {  
      int     from  = trc.from(key);
      int     to    = trc.to(key);
      TString fname = trc.field_name(key); 
      TString field = record.sub(from-1,to); 
      int     flag  = trc.flag(key);
      int     dec   = trc.flag_bis(key);
      
      TRecfield campo (*_deppart,fname);
      if (campo.type() == _realfld)
      { 
        TString sign,importo;
                    
        importo = field;            
        strip_zero(importo);
        if (importo.not_empty())
        {
          if (fname == PART_IMPORTO)
          {
            sign  = record.sub(166,167); 
            if (sign == "-")
              field = sign << importo;
            else
              field = importo;
          }                         
          if (fname == PART_IMPOSTA)
          {
            sign  = record.sub(181,182);
            if (sign == "-")
              field = sign << importo;        
            else
              field = importo;
          }
          if (fname == PART_SPESE)
          {
            sign  = record.sub(196,197);
            if (sign == "-")
              field = sign << importo;        
            else 
              field = importo;
          }
          if (fname == PART_IMPORTOVAL)
          {
            sign  = record.sub(228,229);
            if (sign == "-")
              field = sign << importo;        
            else
              field == importo;
          }
          if (fname == PART_IMPTOTDOC)
          {
            sign  = record.sub(253,254);
            if (sign == "-")
              field = sign << importo;        
            else 
              field = importo;
          } 
          if (fname == PART_IMPTOTVAL)
          {
            sign  = record.sub(268,269);
            if (sign == "-")
              field = sign << importo;        
            else 
              field = importo;
          }
          if (fname == PART_RITENUTE)
          {
            sign  = record.sub(285,286);
            if (sign == "-")
              field = sign << importo;        
            else 
              field = importo;
          }
          if (fname == PART_ABBUONI)
          {
            sign  = record.sub(301,302);
            if (sign == "-")
              field = sign << importo;        
            else 
              field = importo;
          }
          if (fname == PART_DIFFCAM)
          {
            sign  = record.sub(319,320);
            if (sign == "-")
              field = sign << importo;        
            else 
              field = importo;
          }
        }
        else
          field = importo;  
      }  

      if (flag == 3)
      { 
        if (dec > 0)
          decimali(field,dec);
            
        real appoggio (field);
        field = appoggio.string();
      }
      
      if (fname == PART_NREG)
      {
        long numreg = atol(field);
        field.format("%7ld", numreg);        
      }
      
      if (fname == PART_GRUPPO || fname == PART_CONTO || fname == PART_GRUPPOCL
          || fname == PART_CONTOCL || fname == PART_NUMRIG)
      {
        int app = atoi(field);
        field.format("%3d", app);
      }
      
      if (fname == PART_ANNO || fname == PART_NRIGA)
      {
        int app = atoi(field);
        field.format("%4d", app);
      }
      
      if (fname == PART_SOTTOCONTO)
      {
        long sottoc = atol(field);
        field.format("%6ld", sottoc);
      }

      if (flag == 2)
      {
        TString f = converti(field,TRUE);
        _deppart->put(fname,f);
      }
      else
        _deppart->put(fname, field);
          
      numfield++;
      key.format("%2s%d", (const char*) sigla,numfield);
    }
    while (trc.is_key((const char*) key));    
  }

  _tpart->zero();
  _tpart->curr() = *_deppart;
      
  if (_tpart->read() == NOERR)     
  {   
    _tpart->zero();
    _tpart->curr() = *_deppart;
    _tpart->rewrite();
  }
  else
  {
    _tpart->zero();
    _tpart->curr() = *_deppart;     
    _tpart->write();    
  }
  _prog->addstatus(1);  
}

void TTransfer_file::write_scadenze(TString& record)
{ 
  TString      sigla,key;
  int          numfield = 1;   
  TMappa_trc&  trc  = mappa();
  
  sigla     = record.mid(0,2);
  key.format("%2s%d", (const char*)sigla,numfield);

  _depscad->zero();    
      
  if (trc.is_key((const char *) key)) 
  {    
    do
    {  
      int     from  = trc.from(key);
      int     to    = trc.to(key);
      TString fname = trc.field_name(key); 
      TString field = record.sub(from-1,to); 
      int     flag  = trc.flag(key);
      int     dec   = trc.flag_bis(key);
      
      TRecfield campo (*_depscad,fname);
      if (campo.type() == _realfld)
      { 
        TString sign,importo;
                    
        importo = field;            
        strip_zero(importo);
        if (importo.not_empty())
        {
          if (fname == SCAD_IMPORTO)
          {
            sign  = record.sub(116,117); 
            if (sign == "-")
              field = sign << importo;
            else
              field = importo;
          }                         
          if (fname == SCAD_IMPORTOVAL)
          {
            sign  = record.sub(131,132);
            if (sign == "-")
              field = sign << importo;        
            else
              field = importo;
          }
          if (fname == SCAD_IMPORTOPAG)
          {
            sign  = record.sub(171,172);
            if (sign == "-")
              field = sign << importo;        
            else 
              field = importo;
          }
        }
        else
          field = importo;  
      }  
      
      if (flag == 3)
      { 
        if (dec > 0)
          decimali(field,dec);
            
        real appoggio (field);
        field = appoggio.string();
      }
      
      if (fname == SCAD_GRUPPO || fname == SCAD_CONTO)
      {
        int app = atoi(field);
        field.format("%3d", app);
      }                          
      
      if (fname == SCAD_ANNO || fname == SCAD_NRIGA || fname == SCAD_NRATA)
      {
        int app = atoi(field);
        field.format("%4d", app);
      }
      
      if (fname == SCAD_SOTTOCONTO)
      {
        long app = atol(field);
        field.format("%6ld", app);
      }
      
      if (flag == 2)
      {
        TString f = converti(field,TRUE);
        _depscad->put(fname,f);
      }
      else
        _depscad->put(fname, field);
          
      numfield++;
      key.format("%2s%d", (const char*) sigla,numfield);
    }
    while (trc.is_key((const char*) key));    
  }

  _tscad->zero();
  _tscad->curr() = *_depscad;
      
  if (_tscad->read() == NOERR)     
  {   
    _tscad->zero();
    _tscad->curr() = *_depscad;
    _tscad->rewrite();
  }
  else
  {
    _tscad->zero();
    _tscad->curr() = *_depscad;     
    _tscad->write();    
  }
  _prog->addstatus(1);  
}

void TTransfer_file::write_pagsca(TString& record)
{ 
  TString      sigla,key;
  int          numfield = 1;   
  TMappa_trc&  trc  = mappa();
  
  sigla     = record.mid(0,2);
  key.format("%2s%d", (const char*)sigla,numfield);

  _deppagsca->zero();    
      
  if (trc.is_key((const char *) key)) 
  {    
    do
    {  
      int     from  = trc.from(key);
      int     to    = trc.to(key);
      TString fname = trc.field_name(key); 
      TString field = record.sub(from-1,to); 
      int     flag  = trc.flag(key);
      int     dec   = trc.flag_bis(key);
      
      TRecfield campo (*_deppagsca,fname);
      if (campo.type() == _realfld)
      { 
        TString sign,importo;
 
        importo = field;            
        strip_zero(importo);
        if (importo.not_empty())
        {
          if (fname == PAGSCA_IMPORTO)
          {
            sign  = record.sub(61,62); 
            if (sign == "-")
              field = sign << importo;
            else
              field = importo;
          }                         
          if (fname == PAGSCA_IMPORTOVAL)
          {
            sign  = record.sub(76,77);
            if (sign == "-")
              field = sign << importo;        
            else
              field = importo;
          }
          if (fname == PAGSCA_ABBUONI)
          {
            sign  = record.sub(94,95);
            if (sign == "-")
              field = sign << importo;        
            else 
              field = importo;
          }
          if (fname == PAGSCA_DIFFCAM)
          {
            sign  = record.sub(111,112);
            if (sign == "-")
              field = sign << importo;        
            else
              field == importo;
          }
          if (fname == PAGSCA_RITENUTE)
          {
            sign  = record.sub(126,127);
            if (sign == "-")
              field = sign << importo;        
            else 
              field = importo;
          }
        }
        else
          field = importo;  
      }  
      
      if (flag == 3)
      { 
        if (dec > 0)
          decimali(field,dec);
            
        real appoggio (field);
        field = appoggio.string();
      }
      
      if (fname == PAGSCA_GRUPPO || fname == PAGSCA_CONTO  ||
          fname == PAGSCA_GRUPPOC || fname == PAGSCA_CONTOC)
      {
        int app = atoi(field);
        field.format("%3d", app);
      }                          
      
      if (fname == PAGSCA_SOTTOCONTO || fname == PAGSCA_SOTTOCONTC)
      {
        long app = atol(field);
        field.format("%6ld", app);
      }                           
      
      if (fname == PAGSCA_ANNO || fname == PAGSCA_NRIGA ||
          fname == PAGSCA_NRATA || fname == PAGSCA_NRIGP)
      {
        int app = atoi(field);
        field.format("%4d", app);
      }
      
      if (flag == 2)
      {
        TString f = converti(field,TRUE);
        _depmov->put(fname,f);
      }
      else
        _deppagsca->put(fname, field);
          
      numfield++;
      key.format("%2s%d", (const char*) sigla,numfield);
    }
    while (trc.is_key((const char*) key));    
  }

  _tpagsca->zero();
  _tpagsca->curr() = *_deppagsca;
      
  if (_tpagsca->read() == NOERR)     
  {   
    _tpagsca->zero();
    _tpagsca->curr() = *_deppagsca;
    _tpagsca->rewrite();
  }
  else
  {
    _tpagsca->zero();
    _tpagsca->curr() = *_deppagsca;     
    _tpagsca->write();    
  }
  _prog->addstatus(1);  
}

// -----------------------------------------------------------------------
// Mappa dei campi da trasferire
// -----------------------------------------------------------------------

void TMappa_trc::leggi_modulo(const char* tracciato)
{
  TScanner      s(tracciato);
  TString16     key,sigla;
  
  while (s.ok())
  {
    const TString& line = s.line();
    if (line[0] == '#') continue; //Perche' e' un commento

    TToken_string* record = new TToken_string(line);
    sigla  = record->get(0);
    long    numrec = record->get_long(1);
    key.format("%2s%d", (const char*)sigla,numrec);

    add(key, record);
  }          
#ifdef DBG  
  long item = items();
#endif  
}

int TMappa_trc::from(const char* key)
{
  TToken_string * data = (TToken_string *) objptr(key);
  return data->get_int(2);
}

int TMappa_trc::to(const char* key)
{
  TToken_string * data = (TToken_string *) objptr(key);
  return data->get_int(3);
}

int TMappa_trc::logicnum(const char* key)
{
  TToken_string * data = (TToken_string *) objptr(key);
  return data->get_int(4);
}

const char* TMappa_trc::field_name(const char* key)
{
  TToken_string * data = (TToken_string *) objptr(key);
  return data->get(5);
}

int TMappa_trc::flag(const char* key)
{
  TToken_string * data = (TToken_string *) objptr(key);
  return data->get_int(6);
}

int TMappa_trc::flag_bis(const char* key)
{
  TToken_string * data = (TToken_string *) objptr(key);
  return data->get_int(7);
}

extern int get_error(int err);

int packfile(bool vis, int num, TString& name)
{
  int err=NOERR;  
  TDir d;
  
  d.get(num,_nolock, _nordir,_sysdirop);
  d.get(num,_nolock, (d.is_com()) ? _comdir : _nordir);

  err=DB_packfile(vis, name, d.eod());
  if (err != NOERR) err = get_error(err);
#ifdef DBG  
  if (err != NOERR) error_box("Errore in compattamento dati.\nFile %d : %d", d.num(),err);
#endif
  return err;
}


int packindex(bool vis, int num, TString& name)
{
  int err=NOERR;
  TRecnotype peod;
  TTrec r;
  TDir d;
  
  d.get(num,_nolock, _nordir,_sysdirop);
  d.get(num,_nolock, (d.is_com()) ? _comdir : _nordir);
  r.get(num);                
  err=DB_packindex(vis, name, r.rec(), &peod,0);
  if (err != NOERR) err = get_error(err);

#ifdef DBG
  if (err != NOERR) error_box("Errore in compattamento indici.\nFile %d : %d", d.num(),err);
#endif
  return err;
}

int pack(bool vis, int num, TString& name)
{
  int err=NOERR;
  
  if ((err=packfile(vis, num, name))==NOERR)
    err=packindex(vis, num, name); 
  return err;
}

const char* converti (TString& data_AS400,bool anno_di_quattro)
{ 
  if (data_AS400 == "000000" || data_AS400 == "00000000") return TEMP = "";
  
  if (anno_di_quattro)
  {
    TEMP = data_AS400.mid(6,2);
    TEMP << "-" << data_AS400.mid(4,2);
    TEMP << "-" << data_AS400.mid(0,4);  
  }
  else
  {
    TEMP = data_AS400.mid(4,2);
    TEMP << "-" << data_AS400.mid(2,2);
    TEMP << "-" << "19" << data_AS400.mid(0,2);
  }  
  return TEMP;
}

const char* riconverti (TString& data_PC,bool anno_di_quattro)
{                                           
  if (anno_di_quattro)
  {
    TEMP = data_PC.mid(6,4);
    TEMP << data_PC.mid(3,2);
    TEMP << data_PC.mid(0,2);
  }
  else
  {
    TEMP = data_PC.mid(8,2);
    TEMP << data_PC.mid(3,2);
    TEMP << data_PC.mid(0,2);  
  }
  return TEMP;
}

void TTransfer_file::datafine_esprec(const int aep, TDate& datacomp)
{
/* Guy: Oink!
  TTable esc("ESC");
  for (int err = esc.first(); err == NOERR; err = esc.next())
  {
    const anno = esc.get_int("CODTAB");  
    if (anno == aep)
      datacomp = esc.get("D1");      
  } 
*/    
  TEsercizi_contabili esc;
  if (esc.exist(aep))
    datacomp = esc[aep].fine();
}
               
int date2esc(const TDate& d, int* prevesc)
{                  
  TEsercizi_contabili esc;
  int anno = esc.date2esc(d);
  if (prevesc)
    *prevesc = esc.pred(anno);
  return anno;
}

