#include <stdlib.h>
#include <ctype.h>

#include <applicat.h>
#include <isam.h>
#include <mask.h>
#include <prefix.h>
#include <printer.h>
#include <progind.h>
#include <urldefid.h>
#include <utility.h>
#include <validate.h>
#include <extcdecl.h>
#include <execp.h>

#if XVT_OS == XVT_OS_WIN
#define STRICT
#include <windows.h>
#endif

#include "ba1.h"
#include "ba1100.h"

#if XVT_OS==XVT_OS_SCOUNIX
#define DIRSIZ   14
struct direct
{
  unsigned short d_ino;
  char           d_name[DIRSIZ];
};
#else
#include <errno.h>
#include <dos.h>
#endif

#define History_file "conv.his"

class TManutenzione_app : public TApplication
{
  TDir_sheet* _browse;
  TArray _dirs;
  TArray _recs;
  TMask* _mask;
  long _firm;
  long _level;
  long _history_firm;
  TRec_sheet* _rec;

protected:
  virtual bool menu (MENU_TAG);
  virtual bool create () ;
  virtual bool destroy();
  void insert_riga(long, TToken_string&);
  void edit_riga(long, TToken_string&);
  void delete_riga();
  virtual bool extended_firm() const { return TRUE; }
  void update();
  void update_dir();
  void convert_dir();
  virtual void print();
  virtual void do_print(TPrinter & p, TRec_sheet & r);
  const char* dumpfilename(const FileDes& dep) const;
  void load_des();
  void open_history();
  void put_history(const char* firm);
  void close_history();
  void dump_trc(const char * dir, const bool des_too, const long modules);

public:

  TManutenzione_app() : _browse(NULL), _rec(NULL), _mask(NULL), _firm(0), _level(0) {}
};

HIDDEN void build_filelist(const char *path, TArray & list)
{
#if XVT_OS==XVT_OS_SCOUNIX
  struct directx
  {
    ino_t       d_ino;
    char        d_name[DIRSIZ + 1];
  } dlink;
  int   fd;

  if ((fd = open(path, 0)) == -1)
    return;
  dlink.d_name[DIRSIZ] = '\0';
  while(read(fd, &dlink, sizeof(struct direct)) ==
        sizeof(struct direct))
  {
    if (dlink.d_ino > 0)
    {
      TFixed_string dname(dlink.d_name);

      if (dname.find(".des") > 0 && dname[0] == 'd' && !isdigit(dname[1]))
        list.add(dname.mid(1,3));
    }
  }
  close(fd);
#else
  _find_t f;

  if (_dos_findfirst("recdesc/d???.des", _A_NORMAL, &f) == 0)
  {
    bool one_to_add = TRUE;
    while (one_to_add)
    {
      TString80 dname(f.name);

      if (!isdigit(dname[1]))
        list.add(dname.mid(1,3));
      one_to_add = _dos_findnext(&f) == 0;
    }
  }
#endif
}

void TManutenzione_app::do_print(TPrinter & p, TRec_sheet & r)

{
  const char* table[] =  {"", "Alfanumerico", "Intero", "Intero Lungo",
                          "Reale", "Data", "Intero", "Carattere",
                          "Booleano", "Intero Zerofilled",
                          "Intero Lungo Zerofilled","Memo"};
  TPrintrow row;
  TToken_string s;
  TParagraph_string d("", 25);
  TConfig * descr = NULL;
  TTrec & rec = *r.rec();
  TDir & dir = *r.dir();
  const char * descfname = r.descfname();
  TString16 tab(r.tab());
  const bool istab = tab.not_empty();

  tab.upper();
  if (fexist(descfname))
    descr = new TConfig(descfname, DESCPAR);

  const bool hasdescr = descr != NULL;

  row.reset();
  if (istab)
    row.put(format("Lista tabella %s ", (const char *) tab), 2);
  else
    row.put(format("Lista tracciato %s (%s)", dir.des(), dir.name()), 2);
  row.put("Pag. @#", 69);
  p.setheaderline(2, row);
  row.reset();
  row.put("Nome", 7);
  row.put("Tipo", 18);
  row.put("Lun.", 38);
  row.put(" Dec.", 43);
  row.put("Pos.", 48);
  row.put("Descrizione", 53);
  p.setheaderline(4, row);
  p.setbackground("l[1,6,78,6]");
  for (int i = 0; i < rec.fields(); i ++)
  {
    row.reset();
    s = rec.fielddef(i);
    TString16 name = s.get();
    row.put(format("%3d", i + 1), 2);
    row.put(name, 7);
    row.put(table[s.get_int()], 18);
    row.put(format("%4d", s.get_int()), 38);
    row.put(format("%4d", s.get_int()), 43);
    row.put(format("%4d", rec.rec()->Fd[i].RecOff), 48);
    const char *wd = NULL;

    d = "";
    if (hasdescr)
      d = descr->get(name);
    if (!istab || d.not_empty())
    {
      if (hasdescr)
      {
        wd = d.get();
        if (wd != NULL)
          row.put(wd, 53);
      }
      p.print(row);
      wd = d.get();
      while(wd != NULL)
      {
        row.reset();
        row.put(wd, 53);
        p.print(row);
        wd = d.get();
      }
    }
  }
  p.formfeed();
  row.reset();
  row.put("Espressione chiave", 7);
  row.put("Duplicabile", 68);
  p.setheaderline(4, row);
  for (i = 0; i < rec.keys(); i ++)
  {
    row.reset();
    s = rec.keydef(i);
    row.put(format("%3d", i + 1), 2);
    row.put(s.get(), 7);
    row.put(*s.get() == 'X' ? "Si" : "No", 68);
    p.print(row);
  }
  p.formfeed();
  if (hasdescr)
    delete descr;
}

void TManutenzione_app::print()

{
  TPrinter& p = printer();

  p.open();
  p.headerlen(6);
  p.footerlen(4);
  if (_rec == NULL)
  {
    TDir d;

    d.get(LF_DIR);
    int items = (int)d.eod();
    TProgind *pi;
    pi = new TProgind(items,"Stampa tracciati record archivi", TRUE, TRUE, 63);

    pi->setstatus(2);

    for (int i = 2 ; !pi->iscancelled() && i <= items; i++)
    {
      d.get(i);
      if (d.len() > 0)
      {
        TRec_sheet r(i, "");
        pi->addstatus(1);
        do_print(p, r);
      }
    }

    delete pi;
    TArray list;

    build_filelist(DESCDIR, list);
    items = list.items();

    pi = new TProgind(items,"Stampa descrizione tabelle", TRUE, TRUE, 63);

    for (i = 0; !pi->iscancelled() && i < items; i++)
    {
      TString & tab = (TString &) list[i];
      TRec_sheet r(4, tab);

      pi->addstatus(1);
      do_print(p, r);
    }
    delete pi;
  }
  else do_print(p, *_rec);
  p.close();
}

bool TManutenzione_app::create() // initvar e arrmask

{
  TApplication::create();

  _firm = get_firm();
  TString sw(argc()>2 ? argv(2) : "");
  
  if (argc() > 2 && sw == "-C")
  {
    update();
    return FALSE;
  }
  else
  {
    if (sw == "-D")
    {
      const int c = argc();
      bool des_too = 1;  // Anche le descrizioni
      long modules = -1; // Tutti i moduli
      if (c < 4)
      {
        error_box("Usage: BA1 -0 -D <directory> [0|1] [<module number>]");
        return FALSE;
      }
      TFilename dir(argv(3));
      if (!fexist(dir))
      {
        error_box("Non esiste il direttorio %s", (const char*)dir);
        return FALSE;
      }
      if (c == 5)
        des_too = (bool)atoi(argv(4));
      if (c == 6)
        modules = atol(argv(5));
      prefix().set("");
      load_des();
      dump_trc(dir,des_too,modules);
      return FALSE;
    }
    else
      if (!set_firm())
        return FALSE;
   load_des();
   
   
   const bool superprassi = user() == "PRASSI";
    _mask = new TMask ("ba1100a");
    _browse = new TDir_sheet ("Manutenzione file di sistema", superprassi ? 0xC : 0x8);

    if (superprassi)
    {
      _browse->add_button(DLG_INSFILE, "~Inserisci", K_F6);
      _browse->add_button(DLG_CONVERT, "~Converti", K_F7);
      _browse->add_button(DLG_ADDFILE, "~Aggiungi", K_F8);

      _mask->enable(-1);         // Abilita campi privilegiati
    }

    dispatch_e_menu(BAR_ITEM(1));
  }
  enable_menu_item(M_FILE_PRINT);
  return TRUE ;
}

bool TManutenzione_app::destroy() // releasev e arrmask

{
  if (_firm) set_firm(_firm);
  if (_browse != NULL) delete  _browse;
  if (_mask != NULL) delete  _mask;
  return TApplication::destroy() ;
}


void TManutenzione_app::insert_riga (long riga_sel, TToken_string& riga)
{
  const int logicnum = int(riga_sel) + 1;
  const int num_files = (int)_browse->items();

  _mask->disable(DLG_PACK);
  _mask->disable(DLG_RECORD);
  _mask->disable(DLG_LOAD);
  _mask->disable(DLG_DUMP);
  _mask->show(F_TAB, logicnum >= LF_TABGEN && logicnum <= LF_TAB);
  _mask->hide(FLD_EXTEND);
  _mask->hide(FLD_EOX);
  _mask->set (FLD_NUM, riga.get(0));
  _mask->reset (F_TAB);

  if (_mask->run() == K_ENTER)
  {
    /* shift di uno in avanti degli elementi del direttorio partendo dall'ultimo */
    for (int i=num_files; i>=logicnum; i--)
    {
      _browse->dir()->get (i, _nolock, _nordir, _sysdirop);
      _browse->dir()->put (i + 1, _nordir, _sysdirop);
      _browse->rec()->get (i);
      _browse->rec()->put (i + 1);
    }
    _browse->dir()->set(_mask->get(FLD_NOME), _mask->get_long(FLD_EOD),
                        _mask->get_long(FLD_FLAG), _mask->get (FLD_DESC),
                        _mask->get (FLD_FORMULA));
    _browse->dir()->put(logicnum, _nordir, _sysdirop);
    _browse->rec()->zero();
    _browse->rec()->put(logicnum);
    _browse->dir()->get(LF_DIR);
    _browse->dir()->eod()++;
    _browse->set_items(_browse->dir()->eod());
    _browse->dir()->put(LF_DIR);
  }
}

void TManutenzione_app::open_history()
{
  FILE *fp = fopen(History_file,"r");
  if (fp != NULL)
  {
    char line[16];
    fgets(line,16,fp);
    int l = strlen(line);

    line[l > 0 ? l -1 : 0 ] = '\0';   
    if (l==0) _history_firm = -1;
    else
    _history_firm = atol(line);
  }
  else
  {
    fp = fopen(History_file,"w");
    _history_firm = -1;
  }
  fclose (fp);
}

void TManutenzione_app::put_history(const char* firm)
{
  FILE * fp = fopen(History_file,"w");
  fprintf(fp,"%s\n",firm);
  fclose (fp);
}

void TManutenzione_app::close_history()
{
  // Se la conversione non ha rilevato errori rimuove il file di history.
  remove(History_file);
}

void TManutenzione_app::dump_trc(const char * dir, const bool des_too, const long modules)
{
  TDir d;
  d.get(LF_DIR);
  const int items = (int) d.eod();    
  const long flags = d.flags(); // livello archivi
  TFilename fn(dir);
  fn << "/level.dir";
  {
    ofstream of(fn);
    of << flags << '\n';
  }
  
  TString s("Scarico dei tracciati standard in ");
  s << dir;
  TProgind p(items ? items : 1, s, FALSE, TRUE, 70);
  p.setstatus(1);
  for (int i=2;i<=items;i++) //Salta il primo (dir.gen)
  {
    p.addstatus(1);
    TTrec& rc = (TTrec&)_recs[i];
    TDir&  dr = (TDir&)_dirs[i];
    const long file_mod = (long)abs((int)dr.flags());
    if (modules != -1 && file_mod != modules) continue; // se non fa parte del modulo lo salta
    TFilename descfname;
    descfname.format("%s/d%d.des", DESCDIR, i);
    if (!fexist(descfname)) // crea la descrizione se non esiste
    {                           
      FILE * fd = fopen(descfname, "w");
            
      if (fd != NULL)
        fclose(fd);
    }
    TConfig conf_des(descfname,DESCPAR);
    
    if (des_too) rc.set_des(&conf_des);
    fn = dir;
    fn << "/f";fn << i;
    fn.ext("trr");
    ofstream out(fn);
    out << rc;
    fn.ext("dir");
    ofstream out_dir(fn);
    out_dir << dr;
  }
}

const char* TManutenzione_app::dumpfilename(const FileDes& dep) const
{
  TFilename n; n.tempdir();
#if XVT_OS == XVT_OS_SCOUNIX
  n << '/';
#else
  n << '\\';
#endif
  n << dep.SysName;
  n.strip("$%");
  n.ext("txt");
  n.lower();

  strcpy(__tmp_string, n);
  return __tmp_string;
}

void TManutenzione_app::edit_riga (long riga_sel, TToken_string& riga)

{
  KEY  tasto;
  FileDes  dep;
  TDir d;
  const int logicnum = int(riga_sel) + 1;

  const bool superprassi = user() == "PRASSI";

  _mask->enable(DLG_PACK, superprassi);
  _mask->enable(DLG_RECORD, superprassi);
  _mask->enable(DLG_LOAD, superprassi);
  _mask->enable(DLG_DUMP);

  _mask->show(F_TAB, logicnum >= LF_TABGEN && logicnum <= LF_TAB);
  _mask->set (FLD_NUM, riga.get(0));
  _mask->set (FLD_NOME, riga.get());
  _mask->set (FLD_EOD, riga.get());
  _mask->set (FLD_EOX, riga.get());
  _mask->set (F_LEN, riga.get());
  _mask->set (FLD_DESC, riga.get());
  _mask->set (FLD_FORMULA, riga.get());
  _mask->set (FLD_FLAG, riga.get());
  _mask->reset (FLD_EXTEND);
  _mask->reset (F_TAB);

  const TRecnotype oldeox = _mask->get_long(FLD_EOX);
  const bool com = prefix().is_com() || !*prefix().name();
  const char* name = _mask->get(FLD_NOME);
  const bool enable_extend = (com ? *name != '$' : *name == '$') &&
                             (riga_sel > 0) &&
                             (_mask->get_int(F_LEN) > 0 || oldeox > 0);

  _mask->show(FLD_EXTEND, enable_extend);
  _mask->show(FLD_EOX, enable_extend);
  tasto = _mask->run();

  switch (tasto)
  {
  case K_F4:
    if (logicnum > 1)
    {
      const TFilename filename(_mask->get(FLD_NOME));
      const TString tabella(_mask->get(F_TAB));
      TEdit_file ef;
      ef.browse(logicnum, filename, tabella);
    }
    break;
  case K_F5:
  case K_F6:
  case K_F8:
    if (!superprassi)
    {
      error_box("Funzione non ammessa per l'utente %s", (const char*)user());
      break;
    }
  case K_F7:
  case K_ENTER:
  {
    strcpy (dep.SysName,_mask->get (FLD_NOME));
    dep.EOD = atol(_mask->get (FLD_EOD));
    dep.Flags = atol(_mask->get (FLD_FLAG));
    strcpy (dep.Des,_mask->get (FLD_DESC));
    strcpy (dep.FCalc,_mask->get (FLD_FORMULA));
    const TRecnotype eox = _mask->get_bool(FLD_EXTEND) ? _mask->get_long(FLD_EOX) : oldeox;

    _browse->dir()->get(logicnum, _lock, _nordir, _sysdirop);
    _browse->dir()->set(dep.SysName, dep.EOD, dep.Flags,
                        dep.Des, dep.FCalc);
    _browse->dir()->put(logicnum, _nordir, _sysdirop);

  {
    TSystemisamfile f(logicnum);

    if (eox != oldeox)
    {
      d.get(logicnum);
      TFilename f_name(d.name());
      f_name.ext("dbf");

      if (!fexist(f_name)) f.build(eox);
      else f.extend(eox);
      _browse->dir()->get(logicnum, _nolock, _nordir, _sysdirop);
    }
    if (tasto == K_F5)
    {
      f.packfile();
      f.packindex();
      //Pack supplementare tramite FOXPRO (da togliere con CodeBase 6)
#if XVT_OS == XVT_OS_WIN          
      if (logicnum > 2 && logicnum < 6 && f.status() == NOERR)
        if (fexist("packaga.exe"))
        {
          d.get(logicnum);
          TFilename f_name(d.name());
          f_name.ext("dbf");
          f_name.replace('/','\\'); // A volte rimangono delle slash
          TString cmd("packaga -t");
          cmd << " " << f_name;
          TExternal_app packapp(cmd);
          packapp.run(FALSE,FALSE);
        }
#endif
    }
    else
      if (tasto == K_F6)
      {
        _rec = new TRec_sheet(logicnum, _mask->get(F_TAB));
        _rec->edit();
        delete _rec;
        _rec = NULL;
      }
      else
        if (tasto == K_F7)
        {
          TMask m("ba1100b");

          TFilename nout(dumpfilename(dep));
          m.set(FLD_OUTFILE, nout);

          if (m.run() == K_ENTER)
          {
            nout = m.get(FLD_OUTFILE);
            if (nout.not_empty())
            {
              const char fs = *esc(m.get(FLD_FS));
              const char fd = *esc(m.get(FLD_FD));
              const char rs = *esc(m.get(FLD_RS));
              const bool withdel = m.get_bool(FLD_WITHDEL);
              const int keyno = m.get_int(FLD_KEYNO);
              f.dump(nout, keyno, fs, fd, rs, withdel);
            }
          }
        }
        else
          if (tasto == K_F8)
          {
            TMask m("ba1100c");
            TFilename ninp(dumpfilename(dep));
            m.set(FLD_INFILE, ninp);
            if (m.run() == K_ENTER)
            {
              char fs = *esc(m.get(FLD_FS));
              char fd = *esc(m.get(FLD_FD));
              char rs = *esc(m.get(FLD_RS));
              ninp = m.get(FLD_INFILE);
              f.load(ninp, fs, fd, rs);
            }
          }
  }
  }
    break;
  default:
    break;
  }
}

void TManutenzione_app::delete_riga ()

{
  _browse->dir()->get(LF_DIR);
  if (_browse->dir()->eod() == 0) return;

  int logicnum = (int)_browse->items();

  _browse->dir()->get(logicnum);
  if (yesnocancel_box("Confermare l'eliminzione dell'archivio %s", _browse->dir()->name()) != K_YES) return;
  _browse->dir()->get(LF_DIR);
  _browse->dir()->eod()--;
  _browse->set_items(_browse->dir()->eod());
  _browse->dir()->put(LF_DIR);
  // Azzera il tracciato record del file eliminato.
  TTrec r;
  r.zero();
  r.put(logicnum);

}

#if XVT_OS == XVT_OS_WIN
// Serve per GetFreeSpace
#include <windows.h>
#endif

void TManutenzione_app::update_dir()
{
  // Particolare significato dei flags oltre i 10000:
  // trattasi di files PRASSI, (ad esempio i cespiti) che da noi non vengono toccati,
  // in modo da evitare colpe inutili. Noi aggiorniamo solo i tracciati su dir e trc,
  // ma il file fisico manco lo tocchiamo!!
  const TString pref(prefix().name());
  const bool is_com = prefix().is_com();

  if (prefix().get_codditta() <= _history_firm)
    return;

  const int orig_items = _dirs.last();

  TDir d ;

  d.get(LF_DIR);
  const int items = (int)d.eod();

  TString prompt(128);
  prompt = "Aggiornamento direttorio ";
  if (is_com) prompt << "comune";
  else prompt << " della ditta " << atol(pref) <<".";
#if XVT_OS == XVT_OS_WIN
  prompt << " Memoria libera: " << (long)GetFreeSpace(0)/1024 << " Kbytes.";
#endif

  TProgind p(items ? items : 1, prompt, FALSE, TRUE, 70);
  p.setstatus(1);

  for (int i = 2; i <= items; i++)
  {
    p.addstatus(1);
//    prefix().set("");
    const TDir & ds = (const TDir &) _dirs[i];
    const bool is_firm = ds.is_firm();
    const bool to_create = (is_com ? ds.is_com() : ds.is_firm());
    
//    TString s(ds.name());
    TFilename fd(ds.filename());

    bool towrite = FALSE;

    const long flags = ds.flags();
//    word len = ds.len();
//    prefix().set(pref);
    d.get(i);
    TFilename fs(d.filename());

    if (!fexist(fs))
    {
      if (d.eox() > 0L)
      {
        d.get(i, _nolock, _nordir, _sysdirop);
        d.eod() = 0L;
        d.eox() = 0L;
        d.put(i, _nordir, _sysdirop);
      }
    }
    else
      if (i > 2)
      {
        FILE * f = fopen(fs, "r");
        if (f != NULL)
        {
          fseek(f, 0L, SEEK_END);
          const long size = ftell(f);

          fclose(f);
          if (size > 0L && d.len() > 0)
          {
            TBaseisamfile b(i);
            int err = b.is_valid();
            if (err == NOERR)
            {
              TLocalisamfile f(i);
            }
            else
            {
              if (flags < 10000L && !yesno_box("Il file %d non puo' essere aperto: errore %d. Continuo?",i,err))
                stop_run();
            }
          }
          else
          {
            if (flags < 10000L && to_create )
            {
              remove(d.filename());
              TToken_string idx_names;
              get_idx_names(i, idx_names);
              for (const char * idx_name = idx_names.get(); idx_name != NULL; idx_name = idx_names.get())
                remove(idx_name);
              d.get(i, _nolock, _nordir, _sysdirop);
              d.eod() = 0L;
              d.eox() = 0L;
              d.put(i, _nordir, _sysdirop);
            }
          }
        }
      }
    d.get(i, _nolock, _nordir, _sysdirop);
    if (to_create)
    {
/* non piu' necessario
     if (is_firm)
      {
        TString name(fd);
        fd.cut(0);
        fd << fs.path() << name;
      }
*/

      if (flags < 10000L && fexist(fs) && (fd != fs))
      {
        bool ok = TRUE;
        TFilename path(fd.path());

        path.rtrim(1);
        if (path.not_empty() && !fexist(path))
          ok = make_dir(path);
        if (ok && fcopy(fs, fd))
        {
          TToken_string ts(10),td(10);
          td.cut(0);
          get_idx_names(i,ts);   // Get index names of current file in current dir
          for (int j=1; j<= ts.items() && ok; j++)
          {
            const TFilename fsi(ts.get());
            TFilename       fdi(fd); // Nuovo nome. (Con l'estensione)
            fdi.ext("");
            if (j > 1)  // Means that more indexes are in TToken_string ts
            {
              TString xx=fdi.name();
              if (xx.len() < 8)
                fdi << ('0' + j);
              else
                fdi[8] = ('0' + j);
            }
            fdi.ext(fsi.ext());
            td.add(fdi);
            if (!fcopy(fsi, fdi))
              ok = FALSE;
          }
          if (ok)
          {
            remove(fs);           // Rimuove i files sorgenti. Crea un eventuale .cgp
            fd.ext("cgp");
            FILE *o=NULL;
            if (ts.items() > 1)
            {
              fs.ext("cgp");
              remove(fs);
              o=fopen(fd,"w");
            }
            ts.restart();
            td.restart();
            for (int j=1; j<=ts.items(); j++)
            {
              remove(ts.get());
              if (ts.items() > 1) // Means that fd.cgp must be created
              {
                TFilename ff=td.get();
                ff.ext("");
                ff.rtrim(1);
                fprintf(o,"%s\n",ff.name());
              }
            }
            if (o!=NULL)
              fclose(o);
          }
          else
          {
            remove(fd); // Remove all destinations written
            td.restart();
            for (int j=1; j<=td.items(); j++)
              remove(td.get());
          }
        }
        else
          ok = FALSE;
        if (ok)
        {
          d.set(ds.name(), d.eox(), 0L, ds.des(), d.expr());
          towrite = TRUE;
        }
      }
    }
    else
    {
      towrite = (TString(ds.des()) != d.des());
      if (towrite)
        strcpy((char *) d.des(), ds.des());
    }
    if (towrite)
      d.put(i, _nordir, _sysdirop);
//    d.get(i);
  }  // end of for scope
//  prefix().set(pref);

  if (items >= orig_items) return;

  for (i = items + 1; i <= orig_items; i++)
  {
//    prefix().set("");
//    d.get(i, _nolock, _nordir, _sysdirop);
//    prefix().set(pref);
    TDir d1((TDir &) _dirs[i]);

    d1.set_len(0);
    d1.eox() = 0;
    d1.flags() = 0L;
    d1.put(i, _nordir, _sysdirop);
  }
//  prefix().set(pref);
  d.get(LF_DIR, _nolock, _nordir, _sysdirop);
  d.eod() = orig_items;
  if (d.eox() < d.eod())
    d.eox() = d.eod();
  d.put(LF_DIR, _nordir, _sysdirop);
}

void TManutenzione_app::convert_dir()
{
  const TString pref(prefix().name());
  const bool is_com = prefix().is_com();

  TDir d;

  if (prefix().get_codditta() <= _history_firm)
    return;

  d.get(LF_DIR);
  const int items = (int)d.eod();

  TString s(256);
  s = "Aggiornamento archivi ";
  if (is_com) s << "comuni.";
  else s << "della ditta " << atol (pref) << ".";

#if XVT_OS == XVT_OS_WIN
  s << " Memoria libera: " << (long)GetFreeSpace(0)/1024 << " Kbytes.";
#endif

  TProgind p(items ? items : 1, s, FALSE, TRUE, 70);
  p.setstatus(1);

  for (int i = 2; i <= items; i++)
  {
    p.addstatus(1);
//    prefix().set("");
    const TTrec & rs = (const TTrec &) _recs[i];
    const TDir & ds = (const TDir &) _dirs[i];
    const long flags = ds.flags();
//    prefix().set(pref);
    if (ds.len() > 0)
    {
      if (flags < 10000L)
      {
        TBaseisamfile b(i);
        const int module = abs((int)ds.flags());
        int err = b.is_valid();
        if (err == -60) err=NOERR;
        d.get(i, _nolock, _nordir, _sysdirop);
        if (i > 2 && err != NOERR && ((is_com && d.is_com()) || (!is_com && d.is_firm())))
        {
          if (!yesno_box("Il file %d non puo' essere aperto: errore %d. Continuo?",i,err))
            stop_run();
          else continue;
        }
  
        TSystemisamfile f(i);
  
        f.update(rs);
        
        if (f.status() == 8) // cio' significa che e' accaduto quasi l'irreparabile...
        {
          {
            TLocalisamfile u(LF_USER);
            u.zero(); u.put("USERNAME","PRASSI");
            if (u.read() == NOERR)
            {
              u.zero("AUTSTR");
              u.rewrite();
            }
          }
          stop_run();
        }
        d.get(i, _nolock, _nordir, _sysdirop);
        bool to_create = (is_com ? d.is_com() : d.is_firm());
        const bool actual_create = to_create;
  
        // I files LF_PCON, LF_CAUS, LF_RCAUS, LF_CLIFO, LF_CFVEN, LF_INDSPED
        // vanno creati comunque nel direttorio COM, vuoti, (se non esistono gia').
        if (is_com && !to_create)
          if (i == LF_INDSP || i == LF_CLIFO ||
               i == LF_PCON || i == LF_CAUSALI || i == LF_RCAUSALI)
             to_create = TRUE;
        
        if (to_create && has_module(module, CHK_DONGLE))
        {
          d.get(i);
          TFilename s(d.filename());
          if (!fexist(s))
          {
            TSystemisamfile f(i);
            set_autoload_new_files(actual_create); 
            f.build(10L);
            set_autoload_new_files(TRUE);
          }
        }
      }
      else // altrimenti se i flags sono oltre i fatidici 10000...
      {
        TTrec r(rs);

        d.get(i, _nolock, _nordir, _sysdirop);
        d.set_len(r.len());
        d.put(i, _nordir, _sysdirop);
        r.put(i);
      }  
    }
    else // altrimenti se la dimensione del tracciato e' zero...
    {
      TTrec r(rs);

      r.zero();
      r.put(i);
    }
  }
//  prefix().set(pref);
  d.get(LF_DIR, _nolock, _nordir, _sysdirop);
  d.flags() = _level;
  d.put(LF_DIR, _nordir, _sysdirop);
  put_history(pref);
}

void TManutenzione_app::load_des()
{
  const TString pref(prefix().name());

  _dirs.destroy();
  _recs.destroy();
  _level = prefix().filelevel();

  TDir d;
  TTrec r;

  d.get(LF_DIR,_nolock, _nordir,_sysdirop);
  int items = (int)d.eod();
  long flags = d.flags();
  const bool standard = pref.empty();
  
  if (standard) // carica eventuali nuove descrizioni ed il nuovo livello archivi
  {
     // Cerca in RECDESC i files f[nnn].dir, la cui numerazione inizia da items+1
     TFilename fn;
     TDir td;
     TTrec tr;
     tr.zero();
     fn << DESCDIR << "/level.dir";
     
     if (fexist(fn))
     {
       {
         long fl;
         ifstream level(fn);
         level >> fl;
         if (fl > flags) flags = fl;
       }
       unlink(fn);
     }
     
     for (int xf=2;;xf++)
     {
       fn = DESCDIR;
       fn << "/f" << xf;
       fn.ext("dir");
       if (!fexist(fn) && xf > items) // appena non ne trova uno oltre il numero di items ha finito
        break;
       // altrimenti lo carica nel direttorio standard,
       // aggiungendo un tracciato vuoto
       {
         ifstream in(fn);
         in >> td;
         td.put(xf,_nordir,_sysdirop);
         if (xf > items)
           tr.put(xf);
       }
       unlink(fn);
     }
     xf--;
     d.eod() = (long)xf;
     d.eox() = (long)xf;
     d.flags() = flags;
     d.put(LF_DIR,_nordir,_sysdirop);
  }

  items = (int) d.eod();
  TString80 s("Caricamento descrizioni archivi ");

  if (standard) s << "standard";
  else
    if (prefix().is_com()) s << "comuni";
    else s << " della ditta " << atol (pref);

  TProgind p(items ? items : 1, s, TRUE, TRUE, 70);

  p.setstatus(1);
  for (int i = 2; i <= items; i++)
  {
    p.addstatus(1);
    d.get(i, _nolock, _nordir, _sysdirop);
    r.get(i); 
    if (standard)
    {
      TFilename desc_file;
       
      desc_file << DESCDIR << "/f" << i;
      desc_file.ext("trr");
      if (fexist(desc_file))
      {
        {
          ifstream in(desc_file);
          TFilename descfname;
          
          descfname.format("%s/d%d.des", DESCDIR, i);
                           
          if (!fexist(descfname))
          {                           
            FILE * fd = fopen(descfname, "w");
            
            if (fd != NULL)
              fclose(fd);
          }
          
          TConfig descr(descfname, DESCPAR);
          
          r.set_des(&descr);
          in >> r;
          r.put(i); 
          d.set_len(r.len());
          d.put(i, _nordir, _sysdirop);
          r.set_des();
        }             
        remove(desc_file);
      }
    }
    _dirs.add(d, i);
    _recs.add(r, i);
  }
}

void TManutenzione_app::update()
{
  bool ok = TRUE;

  TIsamfile utenti(LF_USER, FALSE);
  utenti.open(_excllock);

  for (int err = utenti.first(); err == NOERR; err = utenti.next())
  {
    const TString16 u = utenti.get("USERNAME");
    if (u == "PRASSI")
    {
      if (utenti.get("AUTSTR") == "CONVERTING")
      {
        ok = error_box("Impossibile proseguire: esiste gia' conversione in corso");
        break;
      }
      else
      {
        utenti.put("AUTSTR", "CONVERTING");
        utenti.rewrite();
      }
    }
    else
    {
      if (utenti.get_bool("CONNECTED"))
      {
        ok = error_box("La conversione non puo' essere effettuata\n"
                       "mentre l'utente %s e' collegato", (const char*)u);
        break;
      }
    }
  }
  utenti.close();
  if (!ok)
    return;

  open_history();
  long firm = get_firm();
  TString pref;
  if (firm == 0) pref = prefix().name();

  do_events();

  begin_wait();
  prefix().set("");
  load_des();
  prefix().set("com");
/*  if (prefix().filelevel() <= 199502L)
  {
    TExternal_app app("bacnv 4 0");
    app.run();
  } */

  update_dir();
  convert_dir();

  TSystemisamfile ditte(LF_NDITTE);
  ditte.open();

  TString80 s("Conversione archivi ditte.");

  TProgind p(ditte.items() ? ditte.items() : 1, s, TRUE, TRUE, 70);

  p.setstatus(1);
  TString mxs;

  for (ditte.first(); !ditte.eof(); ditte.next())
  {
    const TRecnotype rec = ditte.recno();
    const long codditta = ditte.get_long("CODDITTA");
    mxs = s;
#if XVT_OS == XVT_OS_WIN
    mxs << " Ditta " << codditta << ". Memoria libera: " << (long)GetFreeSpace(0)/1024 << " Kbytes.";
#endif
    p.addstatus(1);
    p.set_text(mxs);
    if (codditta > _history_firm && prefix().exist(codditta))
    {
      ditte.close();
      set_firm(codditta);
      update_dir();
      convert_dir();
      ditte.open();
    }
    ditte.readat(rec);
  }
  ditte.close();

  if (firm > 0) set_firm(firm);
  else prefix().set(pref);
  load_des();

  ok = FALSE;
  while (!ok)
  {
    utenti.open(_excllock);
    ok = utenti.ok();
    do_events();
  }

  utenti.put("USERNAME", "PRASSI");
  if (utenti.read() == NOERR)
  {
    utenti.zero("AUTSTR");
    utenti.rewrite();
  }
  utenti.close();
  close_history();
  end_wait();
}

bool TManutenzione_app::menu(MENU_TAG m)
{
  TToken_string riga;
  long  riga_selezionata;
  bool  done = FALSE;

  _browse->rebuild();

  while (!done)
  {
    disable_menu_item(M_FILE_NEW);

    KEY key = _browse->run();

    if (key != K_ENTER && key != K_ESC && user() != "PRASSI")
    {
      error_box("Operazione non permessa all'utente %s", (const char*)user());
      key = 0;
    }

    switch (key)
    {
    case K_F6:
      riga_selezionata = _browse->selected();
      riga = _browse->row();
      insert_riga (riga_selezionata, riga);
       break;

    case K_ENTER:
      riga_selezionata = _browse->selected();
      riga = _browse->row();
      edit_riga (riga_selezionata, riga);
      break;

    case K_DEL: delete_riga(); break;

    case K_ESC: done = TRUE; close_history(); break;         
      
    case K_F7: 
      update(); break;

    case K_F8:
      _browse->add();
      riga_selezionata = _browse->items() - 1;
      riga = _browse->row(riga_selezionata);
      edit_riga (riga_selezionata, riga);
      break;

    default: break;
    }

    enable_menu_item(M_FILE_NEW);
  }

  return xvt_test_menu_tag(BAR_ITEM(2));
}

int ba1100(int argc, char** argv)
{
  TManutenzione_app a;
  a.run(argc, argv, "Gestione files");
  return 0;
}

