#include <stdio.h>

#include "jdecoder.h"
#include "fistrm_c.h"

#include "app.h"

void output_callback( JPEGDecoder *jd, void *ex, unsigned char r, unsigned char g, unsigned char b ) {
  static int x = 0, y = 0, x_mcu = 0, y_mcu = 0;

  AppBase *self = (AppBase *)ex;
  self->dot(  y+y_mcu, x+x_mcu, b, g, r);

  ++x_mcu;

  if ( (x_mcu % jd->MCU_width) == 0) {
    x_mcu = 0;
    ++y_mcu;

    if ( (y_mcu % jd->MCU_height) == 0 ) {
      y_mcu = 0;
      x += jd->MCU_width;

      if (jd->width <= x) {
        x = 0;
        y += jd->MCU_height;
      }
    }
  }
}

class App : public AppBase {
public:
  App(int x, int y, int w, int h, int d): AppBase(x, y, w, h, d) {}
  void theMain() {
    FileInputStream fis;
    JPEGDecoder jd;

    FIS_initialize(&fis, "test.jpg");
    JD_initialize(&jd, output_callback, this );

    JD_decode( &jd, (InputStream *)&fis );

    JD_finalize( &jd );
    FIS_finalize( &fis );

    update();
  } 
};

int main() {

  App app(10,10,200,100, 24);

  app.run();

  return 0; 
}
