public static ImageIcon generateThumbnail(LibraryModel lmodel) throws IOException
  {
    Log.i("Generating thumbnail for "+lmodel.info.name+" ("+lmodel.info.author+")");
    
    Model model = lmodel.model;
    
    if (model == null)
    {
      lmodel.load();
      model = lmodel.model;
      lmodel.unload();
    }
    
    Dimension size = Settings.values.getThumbnailSize();
    int padding = Settings.values.getThumbnailPadding();
    float ratio = ((float)(size.width)) / (size.height);
    
    Rectangle bound = PieceDrawer.computeRealBounds(model, false);
    
    if (bound == null)
      return new ImageIcon(new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB));
    
    float mratio = ((float)bound.width)/bound.height;
    
    Dimension mbounds = new Dimension(bound.width,bound.height);

    // adjusting width and height to fulfill the specified thumbnail ratio
    if (mratio > ratio)
    {
      float newHeight = bound.width * ratio;
      mbounds.height = (int) (newHeight);
    }
    else if (mratio < ratio)
    {
      float newWidth = bound.height / ratio;
      mbounds.width = (int) (newWidth);
    }
    
    System.out.println(mbounds.height+" - "+bound.height);
    // calculating new padding according to adjusted dimension
    Dimension mpadding = new Dimension((mbounds.width - bound.width)/2,(mbounds.height - bound.height)/2);
    
    PImage image = Main.sketch.createImage(mbounds.width, mbounds.height, PApplet.ARGB);
    
    PieceDrawer.drawModelOnImage(image, mpadding.width-bound.x, mpadding.height-bound.y, model, false);
    BufferedImage output = scaleImage((BufferedImage)image.getImage(), size.width/(float)image.width);

    // add padding if necessary
    if (padding > 0)
    {
      BufferedImage output2 = new BufferedImage(output.getWidth()+padding*2, output.getHeight()+padding*2, BufferedImage.TYPE_INT_ARGB);
      Graphics2D g = (Graphics2D)output2.getGraphics();
      g.drawImage(output, padding, padding, null);
      output = output2;
    }
        
    ImageIO.write(output, "PNG", new File(lmodel.thumbnailName()));

    return new ImageIcon(output);
  }