
static void Model_Free(TModel *pmdl);
static bool Model_Fit(const TModel *pSrcModel,TModel *pDstModel,bool *pKogakiFlag);

static TModel UserModel={0,},UserFitModel={0,};
static bool UserModel_KogakiFlag;

static void UserModel_Init(void)
{
  UserModel.LinesCount=0;
  UserModel.pLines=NULL;
  Model_Free(&UserModel);
  
  UserFitModel.LinesCount=0;
  UserFitModel.pLines=NULL;
  Model_Free(&UserFitModel);
  
  UserModel_KogakiFlag=false;
}

static void UserModel_Free(void)
{
  Model_Free(&UserModel);
  Model_Free(&UserFitModel);
  UserModel_KogakiFlag=false;
}

static bool UserModel_Fit(void)
{
  return(Model_Fit(&UserModel,&UserFitModel,&UserModel_KogakiFlag));
}

static void ModelResults_Add(u32 ModelIndex,double Score);

static bool UserModel_Match(void)
{
  TModel *pusrmdl=&UserFitModel;
  for(u32 midx=0;midx<ModelsCount;midx++){
    if(GetPenDown()==true) return(false);
    TModel *psrcmdl=&pModels[midx];
    if(Model_isEnableChar(psrcmdl->wc)==true){
      if(psrcmdl->LinesCount==pusrmdl->LinesCount){
        double Score=0;
        u32 ScoreCount=0;
        if(psrcmdl->LinesCount!=pusrmdl->LinesCount) StopFatalError(0,"Internal error. LinesCount");
        for(u32 lidx=0;lidx<psrcmdl->LinesCount;lidx++){
          TModelLine *psrcline=&psrcmdl->pLines[lidx];
          TModelLine *pusrline=&pusrmdl->pLines[lidx];
          double difflen=psrcline->TotalLen-pusrline->TotalLen;
          Score+=-abs(difflen)/4;
          ScoreCount++;
          double lastlen=0;
          double sx=psrcline->fx,sy=psrcline->fy;
          double ux=pusrline->fx,uy=pusrline->fy;
          double srcfix0x=0,srcfix0y=0;
          if(psrcline->PointsCount==1){
            TModelLinePoint *psrcpoi=&psrcline->pPoints[0];
            srcfix0x=psrcpoi->x/pusrline->PointsCount; srcfix0y+=psrcpoi->y/pusrline->PointsCount;
            }else{
            if(psrcline->PointsCount!=pusrline->PointsCount) StopFatalError(0,"Internal error. PointsCount");
          }
          for(u32 pidx=0;pidx<pusrline->PointsCount;pidx++){
            TModelLinePoint *pusrpoi=&pusrline->pPoints[pidx];
            if(psrcline->PointsCount==1){
              sx+=srcfix0x; sy+=srcfix0y;
              }else{
              TModelLinePoint *psrcpoi=&psrcline->pPoints[pidx];
              sx+=psrcpoi->x; sy+=psrcpoi->y;
            }
            ux+=pusrpoi->x; uy+=pusrpoi->y;
            double diffx=sx-ux,diffy=sy-uy;
            double reslen=_INS_SQRT((diffx*diffx)+(diffy*diffy));
            Score+=-abs(lastlen-reslen);
            ScoreCount++;
            lastlen=reslen;
          }
        }
        Score/=ScoreCount;
        ModelResults_Add(midx,Score);
      }
    }
  }
  
  return(true);
}

// -------------------------------------------------------------------------------------
