/*****************************************************************************
 *                                                                           *
 * Copyright (c) 2006, 2010 Rowley Associates Limited.                       *
 *                                                                           *
 * This file may be distributed under the terms of the License Agreement     *
 * provided with this software.                                              *
 *                                                                           *
 * THIS FILE IS PROVIDED AS IS WITH NO WARRANTY OF ANY KIND, INCLUDING THE   *
 * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. *
 *****************************************************************************/

#include "spi0df.h"
#include "sdram_pll.c"

int
main(void)
{  
  unsigned applicationSize;
  unsigned applicationAddress;
  unsigned flashPage;
  unsigned sbLoaderSize;
  
  init_sdram_pll();

  SPI0DataFlashInit();  
  if (!SPI0DataFlashIdentify())
    while (1); // error      

  // Skip this program
  sbLoaderSize = *(volatile unsigned *)(0x14);
#if defined(AT91RM9200)
  sbLoaderSize &= 0xff;
  sbLoaderSize *= 512;
#endif
  for (flashPage = 0; (flashPage * SPI0DataFlashPageSize) <= sbLoaderSize; flashPage++);
  // Load application to application address
  applicationSize = *(volatile unsigned *)(0x20);
  applicationAddress = *(volatile unsigned *)(0x24);
  while (applicationSize)
    {
      SPI0DataFlashReadPage(flashPage, (unsigned char *)applicationAddress);
      if (applicationSize > SPI0DataFlashPageSize)
        {
          applicationSize -= SPI0DataFlashPageSize;
          applicationAddress += SPI0DataFlashPageSize;
          flashPage++;
        }
      else
        applicationSize = 0;
    }
  return *(volatile unsigned *)(0x24);
} 

