// Noise.cpp: implementation of the CNoise class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "YUVtoRGB.h"
#include "Subtract.h"
#include "PPMandPGMlibrary.h"
#include "Noise.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CSubtract Sub1;

CNoise::CNoise()
{

}

CNoise::~CNoise()
{

}

void CNoise::NoiseDetection()
{
    FILE *fp;
	char name[400] = "bg.yuv";
	GGImage *yuv = NULL;
	unsigned char *pt;

    Sub1.PickMode(MODE1);
    fp = fopen(name, "rb");

	yuv = AllocGGImagePPM(Sub1.ImageW, Sub1.ImageH);
    int j = 0;
    int a = 0;

    while(fread(yuv->data, Sub1.ImageType/*153600*/, 1, fp) && (j < IMAGES)) //read the YUV data from the YUV file
    {
        pt = yuv->data; 
        Y1 = 0;
        Y2 = 0;
        //average the Y values of n images
        a = 0;
        for (int i = 0; i < Sub1.ImageFor/*38400*/; i++)
		{	
            U = *pt++; //for 320x240
            Y1 = *pt++; //for 320x240
            V = *pt++; //for 320x240
            Y2 = *pt++; //for 320x240

			y1[j][a++] = Y1; //put all the Y1 pixels in an array
			y1[j][a++] = Y2; //put all the Y2 pixels in an array
		}

        j = j + 1;
    }

    for (int x = 0; x < Sub1.ImagePixel/*76800*/; x++)
    {
        AvgY1 = 0;

        for (int z = 0; z < IMAGES; z++)
        {
            AvgY1 += y1[z][x]; //sum pixel-x in the 1st image up to pixel-x in the n th image (sum up n numbers)
        }

        AvgY1a[x] = AvgY1/IMAGES;
    }

	fclose(fp);
    Y1Sum = 0;

    for (int n = 0; n < IMAGES; n++)
    {
        for (int m = 0; m < Sub1.ImagePixel/*76800*/; m++)
        {
            Y1Sum += (y1[n][m] - AvgY1a[m]) * (y1[n][m] - AvgY1a[m]);
        }
    }

    Y1Sum /= Sub1.ImagePixel*10/*768000*/;
    Y1Sum = sqrt(Y1Sum);
    cout<<Y1Sum<<endl;
}
