#include <iostream>
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_OUTLINE_H

struct SegmentCounts {
    unsigned contours = 0;
    unsigned lines = 0;
    unsigned quadratics = 0;
    unsigned cubics = 0;
};

int on_move(const FT_Vector*, void* user) {
    ++static_cast<SegmentCounts*>(user)->contours;
    return 0;
}

int on_line(const FT_Vector*, void* user) {
    ++static_cast<SegmentCounts*>(user)->lines;
    return 0;
}

int on_conic(const FT_Vector*, const FT_Vector*, void* user) {
    ++static_cast<SegmentCounts*>(user)->quadratics;
    return 0;
}

int on_cubic(const FT_Vector*, const FT_Vector*, const FT_Vector*, void* user) {
    ++static_cast<SegmentCounts*>(user)->cubics;
    return 0;
}

bool show_outline(FT_Face face, char character) {
    const auto glyph = FT_Get_Char_Index(face, character);
    if (!glyph || FT_Load_Glyph(face, glyph, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP))
        return false;
    if (face->glyph->format != FT_GLYPH_FORMAT_OUTLINE)
        return false;

    FT_Outline& outline = face->glyph->outline;
    SegmentCounts counts;
    const FT_Outline_Funcs callbacks{on_move, on_line, on_conic, on_cubic, 0, 0};
    if (FT_Outline_Decompose(&outline, &callbacks, &counts))
        return false;

    std::cout << character << ": contours=" << counts.contours
              << ", lines=" << counts.lines << ", quadratic=" << counts.quadratics
              << ", cubic=" << counts.cubics << '\n';
    return true;
}

int main(int argc, char** argv) {
    if (argc != 2) {
        std::cerr << "usage: ./demo SourceSans3-Regular.ttf\n";
        return 1;
    }
    FT_Library library = nullptr;
    if (FT_Init_FreeType(&library)) {
        std::cerr << "Could not initialize FreeType\n";
        return 1;
    }
    FT_Face face = nullptr;
    if (FT_New_Face(library, argv[1], 0, &face)) {
        std::cerr << "Could not open font\n";
        FT_Done_FreeType(library);
        return 1;
    }

    FT_Int major, minor, patch;
    FT_Library_Version(library, &major, &minor, &patch);
    std::cout << "FreeType " << major << '.' << minor << '.' << patch << '\n';
    const bool ok = show_outline(face, 'A') && show_outline(face, 'O');
    FT_Done_Face(face);
    FT_Done_FreeType(library);
    if (!ok)
        std::cerr << "Could not decompose outline\n";
    return ok ? 0 : 1;
}
