//----------------------------------------------------------------------------
//	M3UX - MP3 Playlist export tool
//	(C) 2000 Steven Coallier
//	Source code and executable may be freely distributed provided this
// notice is kept intact.  Enjoy!
//----------------------------------------------------------------------------

#include <stdafx.h>
#include <stdio.h>
#include <wtypes.h>
#include <winbase.h>


int main(int argc, char* argv[])
{
	char	src[1024];			// Source full path (with filename)
	char	dst[1024];			// Destination full path (with filename)
	char	destPath[255];		// Destination path with no filename
	BOOL	exists = FALSE;	// Return value for CopyFile()
	FILE	*m3uFile;			// Pointer to File struct for the source file
	char	inCh;					// File input a char at a time
	int		srcPos;			// Keep track of where we are in source string

	// If we don't have the right number of args, explain why
	if (argc != 3)
	{
		printf("Usage: m3uX [m3uFile] [dest]\n");
		printf(" where m3uFile is a valid mp3 playlist and\n dest is a valid DOS destination path.\n");
		return(1);
	}

	// Save the destination string
	strcpy(destPath, argv[2]);

	// Attempt to open the m3u file
	m3uFile = fopen(argv[1], "r+b");
	if (m3uFile == NULL)
	{
		printf("Couldn't open %s.  Exiting M3UX.\n", argv[1]);
		return(2);
	}

	// Start reading from the file
	inCh = fgetc(m3uFile);		// Prime the pump
	srcPos = 0;						// Start the first source string off at the beginning

	// Loop until the file has no more love to give
	while (inCh != EOF)
	{
		// Build up the "source" line
		src[srcPos] = inCh;

		// Look for LF at end of line
		if (src[srcPos] == 0xd)	
		{
			// Close the string off
			src[srcPos] = '\0';
			inCh = fgetc(m3uFile);	// Skip CR

			// Make sure we have a valid line
			if ((src[0] != '\0') && (src[0] != '#'))
			{
				// Find the filename at the end
				int i = strlen(src);
				BOOL	found = FALSE;
				while ((i) && (found == FALSE))
				{
					if (src[i] == '\\')
					{
						found = TRUE;
						strcpy(dst, &destPath[0]);
						strcat(dst, &src[i + 1]);
					}
					else
					{
						i--;
					}
				}

				// If there seems to be a file, try to copy it
				if (i != 0)
				{
					printf("Copying \'%s\' to %s...", src, dst);
					CopyFile(src, dst, exists);
					if (exists)
					{
						printf("failed\n");
					}
					else
					{
						printf("succeeded\n");
					}
				}
			}

			// Start the next source string fresh
			srcPos = 0;
		}
		else
		{
			srcPos++;
		}
		inCh = fgetc(m3uFile);
	}

	// Be clean.
	fclose(m3uFile);
	
	return 0;						  
}

