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

const int size = 256;
const char* tracciato = "cgtrc.ini";  
const int RIC_SIZE = 512;
HIDDEN char _isam_string[RIC_SIZE];

#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," ");
      }    
  }
}


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;
}



TTransfer_file::TTransfer_file() 
{
  _trasfer     = NULL;    
  _tot_rec     = 0L;
  _numreg_p    = 0L;
  _numreg_piva = 0L;
  _trc.leggi_modulo();

  _npoccas = 0L;
}

TTransfer_file::~TTransfer_file()
{
  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;
  
  if (file_ditta)
    dir << main_app().get_firm_dir() << HEADER;
  else
    dir << firm2dir(0) << HEADER;
    
  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);
      
    }
  }
  
}

void TTransfer_file::canc_file_dir_temp(const char* dir)
{                           
  TString80 path;
  path << dir << "\\header";
  fremove(path);
  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);
  path = "";
  path << dir << "\\tclifo.dbf";
  fremove(path);
  path = "";
  path << dir << "\\tclifo.cdx";
  fremove(path);
  path = "";
  path << dir << "\\tpcon.dbf";
  fremove(path);
  path = "";
  path << dir << "\\tpcon.cdx";
  fremove(path);
  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);
  path = "";
  path << dir << "\\toccas.dbf";
  fremove(path);
  path = "";
  path << dir << "\\toccas.cdx";
  fremove(path);
  path = "";
  path << dir << "\\trmoviva.dbf";
  fremove(path);
  path = "";
  path << dir << "\\trmoviva.cdx";
  fremove(path);
}

bool TTransfer_file::read_control_rec()
{
  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,sizeof(char),size,_trasfer);
  
  _tiporec  = _control_rec.sub(0,2);
  
  if (_tiporec == " 1")
  {    
    _nome_simb  = _control_rec.sub(15,25);
    _ditta      = atol(_control_rec.sub(25,30));
    _nultras    = atoi(_control_rec.sub(30,33));
    tmp         = _control_rec.sub(33,41);
    _dataultras = converti(tmp,TRUE);
    
    _sigle_file = _control_rec.sub(41,50);
    _nrec_file  = _control_rec.sub(50,104); 
    TString ult_file   = _control_rec.sub(240,241);
    TString key        = _control_rec.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::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,sizeof(char),size,_trasfer);
  
  _tiporec  = _control_rec.sub(0,2);
  
  if (_tiporec == " 1")
  {    
    _nome_simb  = _control_rec.sub(15,25);
    _ditta      = atol(_control_rec.sub(25,29));
    _nultras    = atoi(_control_rec.sub(29,32));
    tmp         = _control_rec.sub(32,38);
    _dataultras = converti(tmp,FALSE);
    
    _sigle_file = _control_rec.sub(38,47);
    _nrec_file  = _control_rec.sub(47,101); 
    TString ult_file   = _control_rec.sub(240,241);
    TString key        = _control_rec.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)
{             
  TLocalisamfile comuni (LF_COMUNI);
  TString cap = field;
  
  if (cap.sub(2,3) == "1")
  {
    cap = cap.sub(0,3);
    cap << "00";
  }
  
  comuni.setkey(3);
  comuni.zero();
  comuni.put(COM_CAPCOM, cap);
  if (comuni.read() == NOERR)
    TEMP = comuni.get(COM_COM);
  else
    TEMP = "";
  
  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);
        }
          
        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);
          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::datafine_esprec(const int aep, TDate& datacomp)
{
  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");
  } 
}
               
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;
  real              importo = ZERO;
  
  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 = "";
        }
      }

      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))
}

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)
{
  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);
  
  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%6d", (const char*)app,_npoccas);
  
  //ricerca_comune(com);
  _cod_com = "";
            
  if (cap.not_empty())
    _cod_com = cerca_comune_cap(cap);
  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;
  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);                    
          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;
}                    

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;
}

//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;          
  long  offset = 0L;
    
  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);
    
    _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
  static int    disk_num = 0;  
  long          totr     = 0L;
  TString       sigle,nrec;
  long          nrec_cau,nrec_clifo,nrec_pcon,nrec_mov,nrec_moviva;
  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;
  
  totr  = tot_rec();
  sigle = rec.sub(38,47); 
  nrec  = rec.sub(47,101);
  
  int pos = 0;
  
  if (sigle.find('W') >= 0)
  {
    _tmpcaus = "%";
    _tmpcaus << path();
    _tmpcaus << "\\" << TEMP_CAUS;
    _tmprcaus = "%";
    _tmprcaus << path();
    _tmprcaus << "\\" << TEMP_RCAUS;
    nrec_cau = atol(nrec.mid(pos,6));
    pos += 6;
  } 
  if (sigle.find('A') >= 0)
  {
    _tmpclifo = "%";
    _tmpclifo << path();
    _tmpclifo << "\\" << TEMP_CLIFO;
    nrec_clifo = atol(nrec.mid(pos,6));
    pos += 6;
  }
  if (sigle.find('P') >= 0)
  {
    _tmppcon = "%";
    _tmppcon << path();
    _tmppcon << "\\" << TEMP_PCON;   
    nrec_pcon = atol(nrec.mid(pos,6));
    pos += 6;
  }
  if (sigle.find('Z') >= 0)
  {
    _tmpmov = "%";
    _tmpmov  << path();
    _tmpmov << "\\" << TEMP_MOV;
    _tmprmov = "%";
    _tmprmov << path();         
    _tmprmov << "\\" << TEMP_RMOV;  
    nrec_mov = atol(nrec.mid(pos,6));
    pos += 6;
  }
  if (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));
    pos += 6;

    TString80 tmpocc = "%";
    tmpocc  << main_app().get_firm_dir();
    tmpocc << "\\" << TEMP_OCC;
    _toccas = new TIsamtempfile(LF_OCCAS, tmpocc, TRUE);
  }
   
  close();
  
  bool ok = TRUE;
   
  scrivi_header(dest,wflag);
  scrivi_causali(nrec_cau);
  scrivi_clifo(nrec_clifo);
  scrivi_pcon(nrec_pcon);
  scrivi_PN(nrec_mov);
  scrivi_IVA(nrec_moviva);

  if (is_delete) delete _toccas;
  
  delete _ttab;
  
  return ok;
}

void TTransfer_file::scrivi_header(const char* dest, const char* wflag)
{
  const word size = 256;
  TString buffer(size);
  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.
    buffer = (const char*) recf;
    
    TString app(227);
    app = buffer.mid(0,220);
    app.insert("0",25); 
    int pre = atoi(app.sub(33,35));
    if (pre <= 25)
      app.insert("20",33);
    else
      app.insert("19",33);
    TString str;
    str.format("%133s", (const char*) " ");
    app.overwrite(str,104);  
    buffer.overwrite(app,0);
    fwrite((char*)(const char*)buffer, 1, size, 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::temp_dir(TString& dir,TString& firm,TString& sigle)
{
  bool header = TRUE;
        
  for (int i = 0; i < sigle.len(); i++)
  {
    char sigla = sigle[i];
                           
    if (header)
    {
      TString orig = dir;  orig << "\\header";
      TString dest = firm; dest << "\\header";
      fcopy(orig,dest);
      header = FALSE;
    }
                                     
    if (sigla == 'W')
    {
      TString orig = dir;  orig << "\\tcaus.cdx";
      TString dest = firm; dest << "\\tcaus.cdx";
      fcopy(orig,dest);
      orig = dir;  orig << "\\tcaus.dbf";
      dest = firm; dest << "\\tcaus.dbf";
      fcopy(orig,dest);
      orig = dir;  orig << "\\trcaus.cdx";
      dest = firm; dest << "\\trcaus.cdx";
      fcopy(orig,dest);
      orig = dir;  orig << "\\trcaus.dbf";
      dest = firm; dest << "\\trcaus.dbf";
      fcopy(orig,dest);            
    }                         
    if (sigla == 'A')
    {
      TString orig = dir;  orig << "\\tclifo.cdx";
      TString dest = firm; dest << "\\tclifo.cdx";
      fcopy(orig,dest);
      orig = dir;  orig << "\\tclifo.dbf";
      dest = firm; dest << "\\tclifo.dbf";
      fcopy(orig,dest);          
    }
    if (sigla == 'P')
    {
      TString orig = dir;  orig << "\\tpcon.cdx";
      TString dest = firm; dest << "\\tpcon.cdx";
      fcopy(orig,dest);
      orig = dir;  orig << "\\tpcon.dbf";
      dest = firm; dest << "\\tpcon.dbf";
      fcopy(orig,dest);          
    }                            
    if (sigla == 'Z')
    {
      TString orig = dir;  orig << "\\tmov.cdx";
      TString dest = firm; dest << "\\tmov.cdx";
      fcopy(orig,dest);
      orig = dir;  orig << "\\tmov.dbf";
      dest = firm; dest << "\\tmov.dbf";
      fcopy(orig,dest);
      orig = dir;  orig << "\\trmov.cdx";
      dest = firm; dest << "\\trmov.cdx";
      fcopy(orig,dest);
      orig = dir;  orig << "\\trmov.dbf";
      dest = firm; dest << "\\trmov.dbf";
      fcopy(orig,dest);          
    }                            
    if (sigla == 'U')
    {
      TString orig = dir;  orig << "\\trmoviva.cdx";
      TString dest = firm; dest << "\\trmoviva.cdx";
      fcopy(orig,dest);
      orig = dir;  orig << "\\trmoviva.dbf";
      dest = firm; dest << "\\trmoviva.dbf";
      fcopy(orig,dest);
      orig = dir;  orig << "\\toccas.cdx";
      dest = firm; dest << "\\toccas.cdx";
      fcopy(orig,dest);
      orig = dir;  orig << "\\toccas.dbf";
      dest = firm; dest << "\\toccas.dbf";
      fcopy(orig,dest);          
    }
  }
}

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

void TMappa_trc::leggi_modulo()
{
  TScanner      s(tracciato);
  TString16     key;
  TToken_string record;
  
  while (s.ok())
  {
    record = s.line();                   
    
    if (record.mid(0,1) == "#") continue; //Perche' e' un commento
    
    TString sigla  = record.get(0);
    long    numrec = record.get_long(1);
    key.format("%2s%d", (const char*)sigla,numrec);

    add(key, record);
  }          
  long item = items();
}

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);
  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;
}

/*HIDDEN*/ const char* converti (TString& data_AS400,bool anno_di_quattro)
{ 
  if (data_AS400 == "000000") 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;
}

/*HIDDEN*/ 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;
}

/*HIDDEN*/ int date2esc(const TDate& d, int* prevesc)
{                   
  if (prevesc) *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;
    if (prevesc) *prevesc = anno; 
  } 
  return 0;
}

