// this script was modified from some code from http://adafruit.com somewhere.
#include "TFTLCD.h"
#include "TouchScreen.h"
#include <SD.h>

#define YP A3  // must be an analog pin, use "An" notation!
#define XM A2  // must be an analog pin, use "An" notation!
#define YM 9   // can be a digital pin
#define XP 8   // can be a digital pin

#define TS_MINX 150
#define TS_MINY 120
#define TS_MAXX 920
#define TS_MAXY 940

// For better pressure precision, we need to know the resistance
// between X+ and X- Use any multimeter to read it
// For the one we're using, its 300 ohms across the X plate
TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);

// The control pins can connect to any pins but we'll use the 
// analog lines since that means we can double up the pins
// with the touch screen (see the TFT paint example)
#define LCD_CS A3    // Chip Select goes to Analog 3
#define LCD_CD A2    // Command/Data goes to Analog 2
#define LCD_WR A1    // LCD Write goes to Analog 1
#define LCD_RD A0    // LCD Read goes to Analog 0
/* For the 8 data pins:
Duemilanove/Diecimila/UNO/etc ('168 and '328 chips) microcontoller:
D0 connects to digital 8
D1 connects to digital 9
D2 connects to digital 2
D3 connects to digital 3
D4 connects to digital 4
D5 connects to digital 5
D6 connects to digital 6
D7 connects to digital 7
*/

// For Arduino Uno/Duemilanove, etc
//  connect the SD card with DI going to pin 11, DO going to pin 12 and SCK going to pin 13 (standard)
//  Then pin 10 goes to CS (or whatever you have set up)
#define SD_CS 10     // Set the chip select line to whatever you use (10 doesnt conflict with the library)

// In the SD card, place 24 bit color BMP files (be sure they are 24-bit!)
// There are examples in the sketch folder

// optional
#define LCD_RESET A4

// Color definitions
#define	BLACK               0 //0x0000
#define	BLUE               31 //0x001F
#define	GREEN            2016 //0x07E0
#define CYAN             2047 //0x07FF
#define	RED             63488 //0xF800
#define MAGENTA         63519 //0xF81F
#define YELLOW          65504 //0xFFE0 
#define WHITE           65535 //0xFFFF

// our TFT wiring
TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET);

// the file itself
File bmpFile;

// information we extract about the bitmap file
int penRadius, bmpWidth, bmpHeight, currentcolor;
uint8_t bmpDepth, bmpImageoffset;

int pageWidth = 320;
int pageHeight = 240;
int numBoxesRow = 8;
int numBoxesCol = 8;
int boxHeight = 40;
int boxWidth = pageHeight/numBoxesCol;
int x, y;
boolean sColorCrLf;
unsigned int sColor, tColor;
char *bfn = "004.txt";

void setup(){
  Serial.begin(115200);
  Serial.println("Paint with a spashscreen\n\nBy:\ncbwp.net!\n\n");
 
  tft.reset();
  
  // find the TFT display
  uint16_t identifier = tft.readRegister(0x0);
  if (identifier == 0x9325) {
    Serial.println("Found ILI9325");
  } else if (identifier == 0x9328) {
    Serial.println("Found ILI9328");
  } else {
    Serial.print("Unknown driver chip ");
    Serial.println(identifier, HEX);
    while (1);
  }  
 
  tft.initDisplay();

  // splash screen
  Serial.print("Initializing SD card...");
  pinMode(10, OUTPUT);

  if (!SD.begin(10)) {
    Serial.println("failed!");
  } else {
    Serial.println("SD OK!");

    bmpFile = SD.open("s002.bmp");

    if (!bmpFile) {
      Serial.println("didnt find image");
    } else if (! bmpReadHeader(bmpFile)) { 
       Serial.println("bad bmp");
    } else {
      Serial.print("image size "); 
      Serial.print(bmpWidth, DEC);
      Serial.print(", ");
      Serial.println(bmpHeight, DEC);
 
      tft.fillScreen(BLACK);
      //tft.setRotation(2);
      bmpdraw(bmpFile, 0, 0); //120, 40);
      //tft.setRotation(0);
      bmpFile.close();
      delay(2000);
    }
  }

  // drawing page
  tft.fillScreen(BLACK);
  drawBox();
  saveBox();
  loadBox();
  currentcolor = RED;
  paletteBox();

  // for debug
  pinMode(13, OUTPUT);
  // get penRadius from analog input
  pinMode(19, INPUT); 
//  genScreen();
//  grabScreen(bfn);
//  readBmpFile(bfn);
}

#define MINPRESSURE 10
#define MAXPRESSURE 1000
boolean paused = false;

void loop(){
  digitalWrite(13, HIGH);
  Point p = ts.getPoint();
  digitalWrite(13, LOW);

  // if you're sharing pins, you'll need to fix the directions of the touchscreen pins!
  //pinMode(XP, OUTPUT);
  pinMode(XM, OUTPUT);
  pinMode(YP, OUTPUT);
  //pinMode(YM, OUTPUT);

  // we have some minimum pressure we consider 'valid'
  // pressure of 0 means no pressing!

  if (p.z > MINPRESSURE && p.z < MAXPRESSURE) {
    // press the bottom of the screen to erase 
    if (p.y < (TS_MINY-5)) { 
      Serial.println("erase");
      tft.fillRect(0,  boxHeight, tft.width(), tft.height()-boxHeight, BLACK);
      paused = false;
      drawBox();
      saveBox();
      loadBox();
    }

    // turn from 0->1023 to tft.width
    p.x = map(p.x, TS_MINX, TS_MAXX, tft.width(), 0);
    p.y = map(p.y, TS_MINY, TS_MAXY, tft.height(), 0);

    // pressing pause/draw button
    boolean changed = false;
    if ((p.x < boxWidth*1) && (p.y < boxHeight*8) && (p.y > boxHeight*7)){
      paused = !paused;  delay(200);  changed = true;
    }
    
    // pressing save button
    if ((p.x < boxWidth*1) && (p.y < boxHeight*7) && (p.y > boxHeight*6)){
      grabScreen(bfn);  delay(200);
    }

    // pressing load button
    if ((p.x < boxWidth*1) && (p.y < boxHeight*6) && (p.y > boxHeight*5)){
      readBmpFile(bfn);  delay(200);
    }

    if (paused){
      if(changed){
        pauseBox();
      }
    } else if (p.y < boxHeight) {
      chooseColor(p.x);
      paletteBox();
    } else {
      penRadius =  analogRead(5);
      penRadius = map(penRadius, 0, 1023, 1, 5);

      if (((p.y-penRadius) > boxHeight) && ((p.y+penRadius) < tft.height())) {
        tft.fillCircle(p.x, p.y, penRadius, currentcolor);
      }
      if (changed){
        drawBox();
      }
    }
  }
}

unsigned int getPixel(int x, int y){
  tft.writeRegister(0x0020, x); // GRAM Address Set (Horizontal Address) (R20h)
  tft.writeRegister(0x0021, y); // GRAM Address Set (Vertical Address) (R21h)
  unsigned int junk = tft.readRegister(0x0022);
  unsigned int c = tft.readRegister(0x0022);
  return c;
}
void genScreen(){
  tft.fillScreen(BLACK);
  Serial.print("Generating screen...");
  sColor = 0;
  for (x=0;x<240;x++){
    for(y=0;y<320;y++){
      tft.drawPixel(x, y, sColor);
      sColor++;
      if(sColor==65536){ sColor=0; }
    }
  }
  Serial.println("done.");
}
void grabScreen(char *f){
  SD.remove(f);
  bmpFile = SD.open(f, FILE_WRITE);

  // if the file opened okay, write to it:
  if (bmpFile) {
    Serial.print("Writing to ");
    Serial.print(f);
    Serial.print("...");
    for (x=0;x<240;x++){
      for(y=0;y<320;y++){
        sColor = getPixel(x, y);
        if (sColor == 2047 || sColor == 65504){ Serial.println(sColor); }
        bmpFile.println(sColor);
      }
    }

    // close the file:
    bmpFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.print("error opening ");
    Serial.println(f);
  }
}
void readBmpFile(char *f){
  tft.fillScreen(BLACK);
  // re-open the file for reading:
  bmpFile = SD.open(f);
  if (bmpFile) {
    Serial.print("Reading from ");
    Serial.print(f);
    Serial.print(" and redrawing screen...");
    // read from the file until there's nothing else in it:
    while (bmpFile.available()) {
      
      tColor = 0;
      sColor = 0;
      for (x=0;x<240;x++){
        for(y=0;y<320;y++){
          sColorCrLf = false;
          while(!sColorCrLf){
            tColor = bmpFile.read();
            if(tColor == 13){
              tColor = bmpFile.read();
              if(tColor == 10){
                //done with line
                //Serial.println(sColor); // debug
                tft.drawPixel(x, y, sColor);
                sColor = 0;
                tColor = 0;
                sColorCrLf = true;
              }
            }else{
              tColor = tColor - 48;
              sColor = sColor*10 +tColor;
            }
          }
        }
      }
      // close the file:
      bmpFile.close();
      Serial.println("done.");
    }
  } else {
    // if the file didn't open, print an error:
    Serial.print("error opening ");
    Serial.println(f);
  }
}
void paletteBox(){
  tft.fillRect(boxWidth*0, 0, boxWidth, boxHeight, RED);
  tft.fillRect(boxWidth*1, 0, boxWidth, boxHeight, YELLOW);
  tft.fillRect(boxWidth*2, 0, boxWidth, boxHeight, GREEN);
  tft.fillRect(boxWidth*3, 0, boxWidth, boxHeight, CYAN);
  tft.fillRect(boxWidth*4, 0, boxWidth, boxHeight, BLUE);
  tft.fillRect(boxWidth*5, 0, boxWidth, boxHeight, MAGENTA);
  tft.fillRect(boxWidth*6, 0, boxWidth, boxHeight, BLACK);
  tft.fillRect(boxWidth*7, 0, boxWidth, boxHeight, WHITE);
  currentColorBox();
}
void drawBox(){
  tft.drawRect(boxWidth*0+0, boxHeight*7+0, boxWidth-0, boxHeight-0, GREEN);
  tft.fillRect(boxWidth*0+1, boxHeight*7+1, boxWidth-2, boxHeight-2, BLACK);
  tft.drawRect(boxWidth*0+2, boxHeight*7+2, boxWidth-4, boxHeight-4, GREEN);
  tft.setRotation(3);
  tft.setCursor(9, 12);
  tft.setTextColor(GREEN);
  tft.setTextSize(1);
  tft.println("DRAW");
  tft.setRotation(0);
}
void pauseBox(){
  tft.drawRect(boxWidth*0+0, boxHeight*7+0, boxWidth-0, boxHeight-0, RED);
  tft.fillRect(boxWidth*0+1, boxHeight*7+1, boxWidth-2, boxHeight-2, BLACK);
  tft.drawRect(boxWidth*0+2, boxHeight*7+2, boxWidth-4, boxHeight-4, RED);
  tft.setRotation(3);
  tft.setCursor(5, 12);
  tft.setTextColor(RED);
  tft.setTextSize(1);
  tft.println("PAUSE");
  tft.setRotation(0);
}
void saveBox(){
  tft.drawRect(boxWidth*0+0, boxHeight*6+0, boxWidth-0, boxHeight-0, BLUE);
  tft.fillRect(boxWidth*0+1, boxHeight*6+1, boxWidth-2, boxHeight-2, BLACK);
  tft.drawRect(boxWidth*0+2, boxHeight*6+2, boxWidth-4, boxHeight-4, BLUE);
  tft.setRotation(3);
  tft.setCursor(48, 12);
  tft.setTextColor(BLUE);
  tft.setTextSize(1);
  tft.println("SAVE");
  tft.setRotation(0);
}
void loadBox(){
  tft.drawRect(boxWidth*0+0, boxHeight*5+0, boxWidth-0, boxHeight-0, CYAN);
  tft.fillRect(boxWidth*0+1, boxHeight*5+1, boxWidth-2, boxHeight-2, BLACK);
  tft.drawRect(boxWidth*0+2, boxHeight*5+2, boxWidth-4, boxHeight-4, CYAN);
  tft.setRotation(3);
  tft.setCursor(88, 12);
  tft.setTextColor(CYAN);
  tft.setTextSize(1);
  tft.println("LOAD");
  tft.setRotation(0);
}
void chooseColor(int c){
  if (c < boxWidth*1) { 
    currentcolor = RED; 
  } else if (c < boxWidth*2) {
    currentcolor = YELLOW; 
  } else if (c < boxWidth*3) {
    currentcolor = GREEN; 
  } else if (c < boxWidth*4) {
    currentcolor = CYAN; 
  } else if (c < boxWidth*5) {
    currentcolor = BLUE; 
  } else if (c < boxWidth*6) {
    currentcolor = MAGENTA; 
  } else if (c < boxWidth*7) {
    currentcolor = BLACK; 
  } else if (c < boxWidth*8) {
    currentcolor = WHITE; 
  }
}
void currentColorBox(){
  switch (currentcolor){
    case RED:
      tft.drawRect(boxWidth*0, 0, boxWidth, boxHeight, WHITE);
    break;
    case YELLOW: 
      tft.drawRect(boxWidth*1, 0, boxWidth, boxHeight, WHITE);
    break;
    case GREEN: 
      tft.drawRect(boxWidth*2, 0, boxWidth, boxHeight, WHITE);
    break;
    case CYAN: 
      tft.drawRect(boxWidth*3, 0, boxWidth, boxHeight, WHITE);
    break;
    case BLUE: 
      tft.drawRect(boxWidth*4, 0, boxWidth, boxHeight, WHITE);
    break;
    case MAGENTA: 
      tft.drawRect(boxWidth*5, 0, boxWidth, boxHeight, WHITE);
    break;
    case BLACK: 
      tft.drawRect(boxWidth*6, 0, boxWidth, boxHeight, WHITE);
    break;
    case WHITE: 
      tft.drawRect(boxWidth*7, 0, boxWidth, boxHeight, RED);
    break;
  }
}

/*********************************************/
// This procedure reads a bitmap and draws it to the screen
// its sped up by reading many pixels worth of data at a time
// instead of just one pixel at a time. increading the buffer takes
// more RAM but makes the drawing a little faster. 20 pixels' worth
// is probably a good place

#define BUFFPIXEL 20

void bmpdraw(File f, int x, int y) {
  bmpFile.seek(bmpImageoffset);
  
  uint32_t time = millis();
  uint16_t p;
  uint8_t g, b;
  int i, j;
  
  uint8_t sdbuffer[3 * BUFFPIXEL];  // 3 * pixels to buffer
  uint8_t buffidx = 3*BUFFPIXEL;
  
  Serial.print("rotation = "); Serial.println(tft.getRotation(), DEC);
  
  for (i=0; i< bmpHeight; i++) {
    // bitmaps are stored with the BOTTOM line first so we have to move 'up'

    if (tft.getRotation() == 3) {
      tft.goTo(x, y+bmpHeight-i); 
    } else if  (tft.getRotation() == 2) {
      tft.goTo(x+i, y);
    } else if  (tft.getRotation() == 1) {
        tft.goTo(x+bmpWidth-i, y+bmpHeight); 
    } else if  (tft.getRotation() == 0) {
      tft.goTo(x+bmpWidth, y+i); 
    }
    
    for (j=0; j<bmpWidth; j++) {
      // read more pixels
      if (buffidx >= 3*BUFFPIXEL) {
        bmpFile.read(sdbuffer, 3*BUFFPIXEL);
        buffidx = 0;
      }
      
      // convert pixel from 888 to 565
      b = sdbuffer[buffidx++];     // blue
      g = sdbuffer[buffidx++];     // green
      p = sdbuffer[buffidx++];     // red
      
      p >>= 3;
      p <<= 6;
      
      g >>= 2;
      p |= g;
      p <<= 5;
      
      b >>= 3;
      p |= b;
     
       // write out the 16 bits of color
      tft.writeData(p);
    }
  }
  Serial.print(millis() - time, DEC);
  Serial.println(" ms");
}

boolean bmpReadHeader(File f) {
   // read header
  uint32_t tmp;
  
  if (read16(f) != 0x4D42) {
    // magic bytes missing
    return false;
  }
 
  // read file size
  tmp = read32(f);  
  Serial.print("size 0x"); Serial.println(tmp, HEX);
  
  // read and ignore creator bytes
  read32(f);
  
  bmpImageoffset = read32(f);  
  Serial.print("offset "); Serial.println(bmpImageoffset, DEC);
  
  // read DIB header
  tmp = read32(f);
  Serial.print("header size "); Serial.println(tmp, DEC);
  bmpWidth = read32(f);
  bmpHeight = read32(f);

  
  if (read16(f) != 1)
    return false;
    
  bmpDepth = read16(f);
  Serial.print("bitdepth "); Serial.println(bmpDepth, DEC);

  if (read32(f) != 0) {
    // compression not supported!
    return false;
  }
  
  Serial.print("compression "); Serial.println(tmp, DEC);

  return true;
}

/*********************************************/

// These read data from the SD card file and convert them to big endian 
// (the data is stored in little endian format!)

// LITTLE ENDIAN!
uint16_t read16(File f) {
  uint16_t d;
  uint8_t b;
  b = f.read();
  d = f.read();
  d <<= 8;
  d |= b;
  return d;
}


// LITTLE ENDIAN!
uint32_t read32(File f) {
  uint32_t d;
  uint16_t b;
 
  b = read16(f);
  d = read16(f);
  d <<= 16;
  d |= b;
  return d;
}
