// nUtil - An utility Library for gnurbs
// Copyright (C) 2008-2026 Eric Bechet
//
// See the LICENSE file for contributions and license information.
// Please report all bugs and problems to <bechet@cadxfem.org>.
//

#include <iostream>
#include <vector>

#include "vtkdisplay.h"

//fonction de chargement du maillage STL
void loadmesh(std::string filename,std::vector<triangle> &mesh);

int main(int argc, char * argv[])
{
  data_container data;
  vtkdisplay display;

  std::vector<triangle> mesh;
  if (argc==2)
  {
    loadmesh(argv[1],mesh);
  }
  else
  {
    loadmesh("mesh.stl",mesh);
  }

  for(int i=0;i<mesh.size();++i) data.add_triangle(mesh[i]);
  display.init_data(data);
  display.display();
  return 0;
}

#ifndef _WIN32
int stricmp ( const char *s1, const char*s2 )
{
  return strcasecmp ( s1,s2 );
}
#endif

//fonction qui charge un fichier STL
void loadmesh(std::string filename,std::vector<triangle> &mesh)
{
  ifstream fe;
  char poub1[255];
  char poub2[255];
  long i,j;
  triangle t;
  double nx,ny,nz;
  std::cout << " chargement de " << filename << " ... ";
  fe.open ( filename.c_str() );

  if ( !fe.fail() )
  {
    fe>>poub1;
    fe.getline ( poub2,255 );

    if ( stricmp ( poub1,"solid" ) ==0 )
    {

      fe >> poub1 >> poub2 >> nx >> ny >> nz ;

      while ( !fe.eof() )
      {
        if ( ( stricmp ( poub1,"endsolid" ) ==0 ) )
        {
          break;
        }

        if ( ( stricmp ( poub1,"facet" ) !=0 ) || ( strcmp ( poub2,"normal" ) !=0 ) )
        {

          fe.close();
          throw 1;
          break;
        }

        fe >> poub1 >> poub2;

        if ( ( stricmp ( poub1,"outer" ) !=0 ) )
        {
          fe.close();
          throw 1;

          break;
        }

        for ( j=0; j<3; ++j )

        {

          fe >> poub1 >> t.pts[j][0] >> t.pts[j][1] >> t.pts[j][2];
//  poub1="vertex"; PUIS coordonnees du point
          if ( ( stricmp ( poub1,"vertex" ) !=0 ) )

          {
            fe.close();
            throw 1;
            break;
          }
        }

        mesh.push_back(t);

        fe >> poub1;
        //poub1=endloop
        fe >> poub2;
        //poub1=endfacet

        fe >> poub1 >> poub2 >> nx >> ny >> nz ; // normale inutilisée ici 
      }
      fe.close();
    }
    else
    {
      fe.close();
      throw 1;
    }
  }
  else
  {
    std::cout << " fichier inexistant" << std::endl;
    throw 1;
  }
  std::cout << mesh.size()  << " triangles."  << std::endl;
}



