// Moshade - Compute average cross section for 3D shapes
// Copyright (C) 2018-2026 Eric Bechet - bechet@cadxfem.org
//
// See the LICENSE file for license information and contributions.
// Please report all bugs and problems to <bechet@cadxfem.org>.

#include "stl_io.h"
#include <fstream>
#include <cstring>
#include <cctype>

//function that loads an STL file in memory (implementation)
void load_stl_mesh(std::string filename,tri_mesh &mesh)
{
  std::ifstream fe;
  char poub1[255];
  char poub2[255];
  long i,j;
  triangle t; // facet
  npoint3 n; // normal 
//  std::cout << " Loading " << filename << " ... ";
  fe.open ( filename.c_str() );

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

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

      fe >> poub1 >> poub2 >> n[0] >> n[1] >> n[2] ;

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

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

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

        fe >> poub1 >> poub2;

        if ( ( mo_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];
          if ( ( mo_stricmp ( poub1,"vertex" ) !=0 ) )

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


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

        fe >> poub1 >> poub2 >> n[0] >> n[1] >> n[2] ; // normal vector
        mesh.add(t,n);
      }
      fe.close();
    }
    else
    {
      fe.close();
      throw 1;
    }
  }
  else
  {
//    std::cout << "File not found" << std::endl;
    throw 1;
  }
//  std::cout << mesh.size()  << " triangles."  << std::endl;
}

int mo_stricmp ( const char *s1, const char*s2 )
{
    int    c1, c2;
    int    cmp = 0;

    if (s1 && s2)
    for (;;)
    {
        c1 = *s1++;
        c2 = *s2++;
        if (c1 && c2)
        {
            c1 = tolower(c1)&0xFF; // 8 bits
            c2 = tolower(c2)&0xFF; // only
            if (c1 < c2)
            {
                cmp = -1;
                break;
            }
            else if (c1 > c2)
            {
                cmp = 1;
                break;
            }
        }
        else
        {
            if (c1)
                cmp = 1;
            else if (c2)
                cmp = -1;
            break;
        }
    }
    return cmp;
}
