/***********************************************************************************/
/* Created By Troy Davis and Caitlin Smart                                         */
/* Built upon ECE492 lab code as well as altera hello world ucii demo              */
/***********************************************************************************/

#include <errno.h>
#include <ctype.h>
#include "altera_avalon_pio_regs.h"
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "includes.h"
#include "i2c/i2c_ctrl.h"
#include "altera_avalon_timer_regs.h"
#include "priv/alt_file.h"
#include "accelerometer/accelerometer.h"
#include "sys/alt_irq.h"
#include "sys/alt_flash.h"
#include "sys/alt_flash_dev.h"
#include "system.h"
#include "alt_types.h"
#include "head.h"


/* Definition of Task Stacks */
#define   TASK_STACKSIZE       2048
#define   NUM_ELEMENTS         12
#define   WAIT_FOREVER         0
#define   HIST_LENGTH          50

#define AUDIO 1

OS_STK    task_accelerometer_stk[TASK_STACKSIZE];
OS_STK    task_wavplayer_stk[TASK_STACKSIZE];
OS_STK    task_sw_stk[TASK_STACKSIZE];

OS_EVENT *SyncQueue;

OS_EVENT *audio_sem;
OS_EVENT *LCD_sem;
OS_EVENT *SPM_sem;

// ****************************GLOBALS********************************** //
//Global flags
int sync_flag = 0; //BUTTON PRESS POLL

float spm_average = 0; //LATEST RATE INFO

FILE* fp; // lcd
// ******************************************************************** //

/* Definition of Task Priorities */
#define TASK_ACCELEROMETER_PRIORITY      1
#define TASK_SW_PRIORITY                 2
#define TASK_WAVPLAYER_PRIORITY          3

extern int current_flash_block; // NEW

//TYPE DEF NEW
typedef struct audio { 
    unsigned int cl[8000];
    UINT16 song_num;
    BYTE Buffer[512];
    struct music0 music[30];
    UINT16 num_music;
    UINT32 j;
    UINT16 fat_addr;
    UINT16 cluster_num;
    UINT16 song_position;
    UINT16 clupsec_num;
    UINT16 data_sector;
} audio_codec;

audio_codec audio; // NEW

// Function declarations
void play_audio(int select,audio_codec *audio);
void audio_init(audio_codec *audio); 

/***********************************************************************************/
/*ACCELEROMETER TASK:                                                              */
/*Monitors the interrupt count register generated by the accelerometer and updates */
/* a queue every five seconds with the pace of the jogger.                         */
/***********************************************************************************/
void task_accelerometer(void* pdata)
{
    char error;   
    int interrupts;
    int count = 0;
    int i;
    int spm_history[HIST_LENGTH];

    init_i2c();
    init_accelerometer();
        
    for(i = 0; i <= HIST_LENGTH-1; i++){ // Calc current average from history 
        spm_history[i] = 1;
        }
    
    while (1)
    { 
        
        interrupts = (int)IORD_32DIRECT(ACCELEROMETER_CONTROLLER_BASE,0);
        printf("interrupts: %d\n",interrupts);
        IOWR_32DIRECT(ACCELEROMETER_CONTROLLER_BASE,0,0); // Clear interrupt count reg
        
        if(count == HIST_LENGTH)
            count = 0; // reset count
            
        OSSemPend(SPM_sem, WAIT_FOREVER, &error);// PROTECT GLOBAL spm_average    
            for(i = 0; i <= HIST_LENGTH-1; i++){ // Calc current average from history 
                if(i == 0){
                spm_average = spm_history[i];
                }
                else{
                spm_average = spm_average + spm_history[i];
                }
            }
        OSSemPost(SPM_sem);// PROTECT GLOBAL spm_average
        
        /*  
            Do this after calculating current average from histoy because we get
            a extra sample this way. ie we can average the past 50 plus the one we
            just got rather than overwrite one of the histories then average 50 
            samples
        */
        spm_history[count] = interrupts; // update history
        
        OSSemPend(SPM_sem, WAIT_FOREVER, &error);// PROTECT GLOBAL spm_average 
            spm_average = (spm_average + spm_history[count])/51; // update average with current sample
            spm_average = spm_average * 120;

            OSSemPend(LCD_sem, WAIT_FOREVER, &error);// Protect LCD writes
                fprintf(fp, "\x1B[1;1H");// Move to top left (x,y) = (1,1)
                fprintf(fp, "\x1B[K");// Clear top line
                fprintf(fp, "SPM: %f \n",spm_average);
            OSSemPost(LCD_sem);// Release LCD writes
        OSSemPost(SPM_sem);// PROTECT GLOBAL spm_average
        
        for(i = 0; i <= HIST_LENGTH-1; i++){ // Calc current average from history 
            if(i == 0){
            printf("{ %d",spm_history[i]);
            }
            else{
            printf(" %d",spm_history[i]);
            }           
        }
        
        printf("}\n");       
        printf("count: %d\n",count);
        OSTimeDlyHMSM(0,0,0,500);
        count++;          
  } 
}

/***********************************************************************************/
/* END ACCELEROMETER TASK                                                          */
/***********************************************************************************/

/***********************************************************************************/
/* MP3 PLAYER TASK:                                                                */
/* Incharge of all aspects of wav player. Decode, play, queue communication, ect.  */
/***********************************************************************************/

void task_wavplayer(void* pdata)
{
    float avg_pace;
    int num; // loop counter
    int file_num = 1; // song number
    int bpm;
    char error;
    
    audio_init(&audio);
    
    while(1){
    file_num = 1;
        
    //Pull spm average from global
    OSSemPend(SPM_sem, WAIT_FOREVER, &error);// PROTECT GLOBAL spm_average
        avg_pace = spm_average;
    OSSemPost(SPM_sem);// PROTECT GLOBAL spm_average
    
    if(avg_pace < 70)
        bpm = 60;
    else if(70 <= avg_pace && avg_pace  < 90)
            bpm = 80;
         else if(90 <= avg_pace && avg_pace  < 110)
                bpm = 100;
              else if(110 <= avg_pace && avg_pace  < 130)
                      bpm = 120;
                   else if(130 <= avg_pace && avg_pace  < 150)
                            bpm = 140;
                        else if(150 <= avg_pace && avg_pace  < 170)
                                bpm = 160;
                             else if(170 <= avg_pace && avg_pace  < 190)
                                    bpm = 180;
                                  else if(190 <= avg_pace && avg_pace  < 210)
                                          bpm = 200;
                                       else if(210 <= avg_pace)
                                                bpm = 220;
    
    printf("bpm: %d\n",bpm);    
    for (num = 0; num < audio.num_music; num++) {
        printf("music.bpm : %d",audio.music[num].bpm);
        printf("bpm : %d",bpm);
        // music bpm falls in range 70 or less(edge case)
        if (bpm == 60 && audio.music[num].bpm < (bpm + 10)){
           break;
        }
        // music bpm is +- 10 average steps per minute
        if ((bpm - 10) <= audio.music[num].bpm && audio.music[num].bpm < (bpm + 10)){
           break;
        }
        // music bpm falls in range 220 or greater(edge case)
        if ((bpm - 10) <= audio.music[num].bpm && bpm == 220){
           break;  
        }
        file_num++;               
    }
    printf("file_num: %d\n",file_num);
    
    //play the wav file 
    play_audio(file_num,&audio);
    
    }
    
}

/*********************************************************************************/
/* END OF MP3 PLAYER TASK                                                        */
/*********************************************************************************/ 

/*********************************************************************************/
/*SYNC TO STEPS PER MIN                                                                  */
/*********************************************************************************/
/*Pends on msg queue from isr, updates global var to resync player to spm*/
void task_sw(void* pdata)
{
    INT8U err;
    int key;

  while(1)
  {
    key =(int)OSQPend(SyncQueue,WAIT_FOREVER, &err);
    if(key == 1)
        sync_flag = 1;
    err = OSQFlush(SyncQueue);
  }

}

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

/*********************************************************************************/
/* SWITCH ISR                                                                    */
/*********************************************************************************/
static void Sync(void* context, alt_u32 id)
{
    INT8U err;
    
    err = OSQPost(SyncQueue,(void *)1);

    IOWR_ALTERA_AVALON_PIO_EDGE_CAP(SWITCH_BASE, 0); // Clear interrupt
}

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


/*********************************************************************************/
/* The main function creates two task, initializes queue and starts multi-tasking*/
/*********************************************************************************/

int main(void)
{ 
  
    OSInit();
  
    // Create Queue
    void * SyncQueueStorage[NUM_ELEMENTS];
    SyncQueue = OSQCreate(SyncQueueStorage,NUM_ELEMENTS);
    if(SyncQueue == NULL)
    {
        printf("error in Queue create\n");
    }
    
    alt_irq_register(SWITCH_IRQ, 0, Sync);
    IOWR_ALTERA_AVALON_PIO_IRQ_MASK(SWITCH_BASE, 1); // Enable interrupts
    IOWR_ALTERA_AVALON_PIO_EDGE_CAP(SWITCH_BASE, 0); // Clear current interrupts

    //Open a file write pipe to LCD
    fp = fopen ("/dev/lcd_0", "w");
    if(fp == NULL){
        printf("Failed to open LCD\n");
    }

    // Initalize Semaphores
    audio_sem = OSSemCreate(1);
    LCD_sem = OSSemCreate(1);
    SPM_sem = OSSemCreate(1);
    
    // CREATE TASKS                
    OSTaskCreateExt(task_wavplayer,
                  NULL,
                  (void *)&task_wavplayer_stk[TASK_STACKSIZE-1],
                  TASK_WAVPLAYER_PRIORITY,
                  TASK_WAVPLAYER_PRIORITY,
                  task_wavplayer_stk,
                  TASK_STACKSIZE,
                  NULL,
                  0);
    
                      
  
  OSTaskCreateExt(task_accelerometer,
                  NULL,
                  (void *)&task_accelerometer_stk[TASK_STACKSIZE-1],
                  TASK_ACCELEROMETER_PRIORITY,
                  TASK_ACCELEROMETER_PRIORITY,
                  task_accelerometer_stk,
                  TASK_STACKSIZE,
                  NULL,
                  0);
  
  
  
  OSTaskCreateExt(task_sw,
                  NULL,
                  (void *)&task_sw_stk[TASK_STACKSIZE-1],
                  TASK_SW_PRIORITY,
                  TASK_SW_PRIORITY,
                  task_sw_stk,
                  TASK_STACKSIZE,
                  NULL,
                  0);
  
  // BEGIN MULTI TASKING
  OSStart();
  
  return 0;
}

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

/************************************************************************/
/* AUDIO INIT                                                           */
/************************************************************************/
void audio_init(audio_codec *audio2) {
    // Pend on the audio semaphore
    char err;
    
    OSSemPend(audio_sem, 0, &err);

    UINT16 num_lyric;
    audio.song_num = 0;
    audio.song_position = 0;

    struct lyric0 lyric[30];

    printf("Please Insert SD Card\n");
    while (SD_card_init()) {
        printf("Please insert a sd card\n");
        usleep(500000);
    }
    // SD card detected
    printf("SD card has been detected\n");

    // Search and update the database from the SD card
    file_list(audio.music, lyric, &audio.num_music, &num_lyric,
            &audio.clupsec_num, &audio.data_sector, &audio.fat_addr);

    usleep(100);

    // Print all .wav files to the screen
    printf("\n.wav files currently on SD card:\n");
    int num;
    int file_num = 0;
    char str[40];
    int d;
    for (num = 0; num < audio.num_music; num++) {
        sscanf(audio.music[num].m_name,"%d %s",&d,str);
        audio.music[num].bpm = d;
        strcpy(audio.music[num].m_name,str);
        printf("#%d = %s\n", ++file_num, audio.music[num].m_name);
        printf("%s bpm = %d\n",audio.music[num].m_name,audio.music[num].bpm);
    }
    
    // Post the semaphore
    OSSemPost(audio_sem);

}

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

/***************************************************************************/
/* PLAY AUDIO FUNCTION                                                     */
/***************************************************************************/
void play_audio(int select,audio_codec *audio2) {
#ifdef AUDIO
    // Pend on the semaphore
    char err;
    
    OSSemPend(audio_sem, 0, &err);
    
    select = select - 1;
    audio.song_num = select;
    
    printf("\nNow playing song number %d: %s\n", select + 1, audio.music[select].m_name);
        
    //LCD print
    OSSemPend(LCD_sem, WAIT_FOREVER, &err);// Protect LCD writes
    fprintf(fp, "\x1B[1;0H");// Move to lower left (x,y) = (1,0)
    fprintf(fp, "\x1B[K");// Clear current line
    fprintf(fp, "\n%s", audio.music[select].m_name);
    OSSemPost(LCD_sem);// Release LCD writes
        
    // Assign value of cluster according to the song selected
    audio.cl[0] = audio.music[audio.song_num].cluster;

    // Assign total cluster belonging to the song to cl[]
    find_cluster(audio.song_num, audio.fat_addr, audio.cl);
    UINT16 i;
    i = 0;    
    while(audio.cl[i] > 1){
     i++; // calc cluster length   
    }

    // Store total data cluster for file to be used for the play loop
    audio.cluster_num = i;
    UINT16 j_base, base;
    UINT16 temporary1, temporary2;
    for (audio.song_position = 0; (audio.song_position < audio.cluster_num) && !sync_flag; audio.song_position++) {
        base = (audio.cl[audio.song_position] - 2) * audio.clupsec_num
                + audio.data_sector;
        j_base = audio.song_position * audio.clupsec_num - base;

        UINT32 j;
        for (j = base; (j < base + audio.clupsec_num) && !sync_flag; j++) //j is the section in the cluster
        {

            // DE2 Demo Code //
            SD_read_lba(audio.Buffer, j, 1); // read function from SD card controller.c
            i = 0;
            while (i < 512 && !sync_flag) {
                if (!IORD(AUDIO_DAC_FIFO_0_BASE,0)) {
                    temporary1 = ((audio.Buffer[i + 1] << 8) | audio.Buffer[i]); // read from SD card

                    IOWR(AUDIO_DAC_FIFO_0_BASE,0,temporary1);

                    i += 2;
                }
            }
            if (j % 64 == 0) {
                temporary2 = temporary1 * temporary1; // power of the signal
            }

        }
    }
    sync_flag = 0;
    OSSemPost(audio_sem);

#endif
}
/******************************************************************************/

