#include <windows.h> // Windows API Functions
#include <stdio.h>
#include <sys/stat.h>

#define WINAMP_WINDOW_NAME	"Winamp v1.x" // WinAmp's Window Name (v1/2/5)
#define MAX_ARRAY_SIZE		65025
#define MAX_STRING_LENGTH	2048

#define IPC_WRITEPLAYLIST	120 // Requires WinAmp 1.666+
#define IPC_GETLISTLENGTH	124 // Requires WinAmp 2.0+
#define IPC_GETFILE			211
#define IPC_GETTITLE		212
#define IPC_ENQUEUEFILE		100
#define IPC_DELETE			101

HINSTANCE wAmphInst = 0;

//PROTOTYPES
int wAmpOpenProcess(HWND wAmphWnd);
int fileExists(char * file);

//MAIN
int main(void)
{
	HWND wAmphWnd = NULL;

	if ((wAmphWnd = FindWindow(WINAMP_WINDOW_NAME, NULL)) == NULL) // If WinAmp isnt running error!
	{
		printf("Error: Winamp isnt currently running, aborting!\n");
		exit(1);
	}

	if (wAmpOpenProcess(wAmphWnd) != 1)
	{
		printf("Error: Couldnt open process, aborting!\n");
		exit(1);
	}

	unsigned short int wAmpTotalSongs = SendMessage(wAmphWnd, WM_USER, NULL, IPC_GETLISTLENGTH), i;
	//char wAmpTitles[MAX_ARRAY_SIZE][MAX_STRING_LENGTH];
	//char wAmpFiles[MAX_ARRAY_SIZE][MAX_STRING_LENGTH];
	for (i = 0; wAmpTotalSongs > 0; i++)
	{
		char songFile[MAX_STRING_LENGTH] = "";
		char songTitle[MAX_STRING_LENGTH] = "";
		unsigned long int wAmpPointerTitle = SendMessage(wAmphWnd, WM_USER, wAmpTotalSongs - 1, IPC_GETTITLE),
			wAmpPointerFile = SendMessage(wAmphWnd, WM_USER, wAmpTotalSongs - 1, IPC_GETFILE);
		ReadProcessMemory(wAmphInst, (LPVOID) wAmpPointerTitle, songTitle, MAX_STRING_LENGTH, NULL);
		ReadProcessMemory(wAmphInst, (LPVOID) wAmpPointerFile, songFile, MAX_STRING_LENGTH, NULL);
		printf("Title: \%s\nFilename: \%s\n", songTitle, songFile);
		// Cant copy too array
		//wAmpFiles[i][MAX_STRING_LENGTH] = "test";
		wAmpTotalSongs--;
	}
	exit(0);
}

int wAmpOpenProcess(HWND wAmphWnd)
{
	DWORD wAmpThreadId = 0, wAmpProcessId = 0;
	wAmpThreadId = GetWindowThreadProcessId(wAmphWnd, &wAmpProcessId);
	wAmphInst = OpenProcess(PROCESS_VM_READ, FALSE, wAmpProcessId);
	if (wAmphInst == 0)
		return 0;
	else
		return 1;
}

int fileExists(char * file)
{
	struct stat buff;
	int i = stat(file, &buff);
	if (i == 0)
		return 1;
	return 0;
}
