<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<Rule xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Rule_Axmedis.xsd">
  <Header>
    <Rule_Name>Mp3splitter</Rule_Name>
    <AXRID>axcprule:9d492bf2-811e-4828-af1f-0bf9328116a4</AXRID>
    <Rule_Version></Rule_Version>
    <Rule_Type>AXCP</Rule_Type>
    <Software_Name></Software_Name>
    <Version_of_software></Version_of_software>
    <Date_of_production>2006-12-21</Date_of_production>
    <Author></Author>
    <Affiliation></Affiliation>
    <URL></URL>
    <Comment></Comment>
    <Last_Modifications>2007-03-22</Last_Modifications>
    <Terminal_ID></Terminal_ID>
    <Cost></Cost>
    <Work_Item_ID></Work_Item_ID>
  </Header>
  <Schedule>
    <Run>
      <Date>2006-12-21</Date>
      <Time>14:29:21</Time>
      <Periodicity Unit="Day">0</Periodicity>
      <Expiration_Date>2006-12-21</Expiration_Date>
      <Expiration_Time>14:29:21</Expiration_Time>
    </Run>
    <Status>Inactive</Status>
  </Schedule>
  <Definition>
    <AXCP_Rule>
      <Arguments>
        <Parameter Name="input_dir" Type="String">c:\\mp3s</Parameter>
        <Parameter Name="out_dir" Type="String">c:\\mp3test_output</Parameter>
      
      </Arguments>
      <Rule_Body>
        <JS_Script name="split_to_file"><![CDATA[/*****
splits an mp3 file and creates a new file
*/

function mp3split_to_file (infile,  // complete filename of input mp3 (e.g. c:\\inputfile.mp3)
                   outfile, // output filename WITHOUT extension (e.g. c:\\outputfile)
                   start,   // split start in seconds (float: eg. 30.0)
                   end)     // split endin seonds (float: eg. 30.0)
{
    if (!existsFile (infile))
    {
        print ("ERROR: Cannot split "+infile+" -- File doesn't exist!");
        return false;
    }
    if (start >= end)
    {
        print ("ERROR: start: "+start+"  end: "+end+"\n--Splitting start time must be smaller than splitting end time! Cannot split "+infile);
        return false;
    }
    var mp3in = new AxResource ();
    var mp3out = new AxResource ();
    mp3in.load (infile);
    if (mp3in.mimeType  == "audio/mpeg") mp3in.mimeType = "audio/x-mpeg";
    else if (mp3in.mimeType != "audio/x-mpeg")
    {
        print ("ERROR: Cannot use \""+mp3in.mimeType+"\" as MimeType input\nAllowed MimeTypes are:\n  audio/mpeg\n  audio/x-mpeg Cannot split "+infile);
        return false;
    }
    // get information on the file (but doesn't seem to work)
    
    var TheMimeType = new Array(1);
    var TheSamplingRate = new Array(1);
    var TheNumChannels = new Array(1);
    var TheBitRate = new Array(1);
    var TheDuration = new Array(1);
    TheMimeType[0] = "";
    TheSamplingRate[0]=0;
    TheNumChannels[0]=0;
    TheBitRate[0]=0;
    TheDuration[0]=0;
    //print ("Retriving info for file \""+mp3_in_filename+"\" please wait...");
    //var getInfoResult = RingtoneAdaptation.getInfo (mp3in, TheMimeType, TheSamplingRate, TheNumChannels, TheBitRate, TheDuration);
    // ONLY FOR TESTING TO-DELETE IN FINAL SCRIPT
    //print (TheMimeType[0]);
    //print (TheDuration[0]);
    // END TO-DELETE
    //print ("splitting file \""+infile+"\" please wait this may take a while...");
    var clipResult = RingtoneAdaptation.clip (mp3in, mp3out, "audio/x-mpeg", start, end);
    //print ("Clip result: "+clipResult);
    //print ("Total seconds: "+TimeString2Int (TheDuration[0]));
    if (clipResult.match ("ERROR") == null)
    {
        mp3out.save (outfile);
        //print ("-- split SUCCESS: Saved splitted file to \""+outfile+".mp3\"");
        //getInfoResult = RingtoneAdaptation.getInfo (mp3out, TheMimeType, TheSamplingRate, TheNumChannels, TheBitRate, TheDuration);
        //print (" FILE INFO:   "+"MimeType: "+TheMimeType[0]+"   ||| Duration (hh:mm:ss:msec): "+TheDuration[0]+"   ||| BitRate: "+TheBitRate[0]);
        return true;
    } 
    return false;
}
/*test
output_path = "c:\\mp3test\\output"
mp3_in_filename = "c:\\mp3test\\aaa.mp3";
mp3_out_filename = "mp3split_out"; // no extension needed: save will automatically add it!
var start_clip = 0.0;
var end_clip = 30.1;
if (!existsDir (output_path)) 
{
    print ("warning: creating directory "+output_path);
    createDir (output_path);
}
mp3split (mp3_in_filename, output_path + "\\" + mp3_out_filename, start_clip, end_clip)
*/]]>
        </JS_Script>
        <JS_Script name="split_to_resource">
          
          <![CDATA[/*****
splits an mp3 file and creates a new Axmedis Resource */
function mp3split_to_resource (infile,  // complete filename of input mp3 (e.g. c:\\inputfile.mp3)
                   start,   // split start in seconds (float: eg. 30.0)
                   end)     // split endin seonds (float: eg. 30.0)
{
    if (!existsFile (infile))
    {
        print ("ERROR: Cannot split "+infile+" -- File doesn't exist!");
        return false;
    }
    if (start >= end)
    {
        print ("ERROR: start: "+start+"  end: "+end+"\n--Splitting start time must be smaller than splitting end time! Cannot split "+infile);
        return false;
    }
    var mp3in = new AxResource ();
    var mp3out = new AxResource ();
    mp3in.load (infile);
    if (mp3in.mimeType  == "audio/mpeg") mp3in.mimeType = "audio/x-mpeg";
    else if (mp3in.mimeType != "audio/x-mpeg")
    {
        print ("ERROR: Cannot use \""+mp3in.mimeType+"\" as MimeType input\nAllowed MimeTypes are:\n  audio/mpeg\n  audio/x-mpeg Cannot split "+infile);
        return false;
    }
    // get information on the file (thanks to Ivan for help on getting this to work)
    var TheMimeType = new Array(1);
    var TheSamplingRate = new Array(1);
    var TheNumChannels = new Array(1);
    var TheBitRate = new Array(1);
    var TheDuration = new Array(1);
    TheMimeType[0] = "";
    TheSamplingRate[0]=0;
    TheNumChannels[0]=0;
    TheBitRate[0]=0;
    TheDuration[0]=0;
    //print ("Retriving info for file \""+mp3_in_filename+"\" please wait...");
    //var getInfoResult = RingtoneAdaptation.getInfo (mp3in, TheMimeType, TheSamplingRate, TheNumChannels, TheBitRate, TheDuration);
    // ONLY FOR TESTING TO-DELETE IN FINAL SCRIPT
    //print (TheMimeType[0]);
    //print (TheDuration[0]);
    // END TO-DELETE
    //print ("splitting file \""+infile+"\" please wait this may take a while...");
    var clipResult = RingtoneAdaptation.clip (mp3in, mp3out, "audio/x-mpeg", start, end);
    //print ("Clip result: "+clipResult);
    //print ("Total seconds: "+TimeString2Int (TheDuration[0]));
    if (clipResult.match ("ERROR") == null)
    {
       
       //print ("-- split SUCCESS: Resource created");
        //getInfoResult = RingtoneAdaptation.getInfo (mp3out, TheMimeType, TheSamplingRate, TheNumChannels, TheBitRate, TheDuration);
        //print (" FILE INFO:   "+"MimeType: "+TheMimeType[0]+"   ||| Duration (hh:mm:ss:msec): "+TheDuration[0]+"   ||| BitRate: "+TheBitRate[0]);
        return mp3out;
    }
    else 
    {
    print (clipResult);
    return false;
    }
    return false;
}]]>
        </JS_Script>
        <JS_Script name="split_to_dirs">
          
          <![CDATA[/* splits files and saves the splitted ones 
in a subdir (same name as input) in the output_dir
input and root-output dirs must be different
*/
function split_to_dir       (in_dir,     // input directory
                            output_dir, // output directory
                            split_start,// split start time in seconds (float) 
                            split_end)  // split end time in seconds (float) 
{
    var added = 0;
    errors = 0;
    var log = "";
    log = log + "****************************************\n**** Trying to Split mp3 files in "+in_dir+" ---> "+output_dir+"\n"+"**** Split start time: "+split_start+"\n**** Split end Time: "+ split_end+"\n\n";
    var date = new Date();
    if (in_dir == output_dir)
    // this is to prevent creating the files in the source directories
    // and clutter them.
    {
        print ("ERROR: Input and root output directories must be different");
        log = log + "\nERROR: Input and root output directories must be different -- "+date.getHours()+":"+date.getMinutes()+"\n";
        appendToFile (output_dir+"\\log.txt" ,log);
        return false;
    }
    if (in_dir == "" || !existsDir (in_dir))
    {
        print ("ERROR: Invalid or non-existing input directory \""+in_dir+"\"");
        log = log + "\nERROR: Invalid or non-existing input directory \""+in_dir+"\"  -- "+date.getHours()+":"+date.getMinutes()+"\n";
        appendToFile (output_dir+"\\log.txt" ,log);
        return false;
    }
    if (!existsDir (output_dir))
    {
        createDir (output_dir);
        print ("WARNING: output directory \""+output_dir+"\" doesn't exist. Creating it");
        log = log + "WARNING: output directory \""+output_dir+"\" doesn't exist. Creating it\n";
    }
    print ("--- Processing mp3 files in "+in_dir+" ---\n-- started at "+ date.getHours()+":"+date.getMinutes());
    log = log + "-- started at "+ date.getHours()+":"+date.getMinutes()+"\n";
    //var output_dir = "c:\\mp3test\\output";
    var files_to_split = getfilelist (in_dir, "*.mp3");
    var subdir_name = strip_filename (in_dir);
    if (files_to_split.length > 15)
    {
        if (files_to_split.length <= 30) print ("***** WARNING! There are "+files_to_split.length+" files to split this may take quite long.... coffee?");
        else if (files_to_split.length <= 60) print ("***** WARNING! There are "+files_to_split.length+" files: this will surely take quite long.... coffee?");
        else print ("***** WARNING! There are "+files_to_split.length+" files: this will surely take long.... coffee (and maybe a snack)?");
    }
    for (i_main=0; i_main < files_to_split.length; i_main++)
    {
        var status = Math.ceil (i_main * 100 /files_to_split.length);
        if (status < 9) print (status+"%    --- processing file "+(i_main+1)+" of "+ files_to_split.length);
        else print (status+"%  --- processing file "+(i_main+1)+" of "+ files_to_split.length);
        var file_to_split = files_to_split[i_main];
        var filename_only = strip_filename (file_to_split);
        filename_only = strip_extension (filename_only);
        var resource_name = strip_filename (file_to_split);
        
        // if filename DO NOT use extension: it will be automatically added!
        var split_output = output_dir +"\\"+subdir_name +"\\" + filename_only + "_split_30s";
             
        if (!existsDir (output_dir +"\\"+subdir_name))
        {
            createDir (output_dir +"\\"+subdir_name);
        }
        
        //use this to split to file.
        if (!mp3split_to_file (file_to_split, split_output, split_start, split_end))
        {
            print ("WARNING: Unable to process "+file_to_split+" see clipping result\n");      
            log = log + "***** WARNING: Unable to process "+file_to_split+" see clipping result\n";
            errors = errors +1;
        }
        else
        {
            added = added +1;
            print ("-- OK: Saved "+ split_output + ".mp3");
            log = log + "+ OK: Saved "+ split_output + ".mp3\n";
        }
    }
    if (added > 0)
    {
        date = new Date();
        if (errors == 0)
        {
            print ("\nSUCCESS: Saved split files in "+output_dir+"\n-- ended at "+ date.getHours()+":"+date.getMinutes()+"\n");
            log = log + "SUCCESS: Saved split files in "+output_dir+"\n-- ended at "+ date.getHours()+":"+date.getMinutes()+"\n"+"\n";
        }
        else
        {
             print ("\nWARNING: Saved split files in "+output_dir+" *** but there were "+ errors+" error(s)***\n-- ended at "+ date.getHours()+":"+date.getMinutes()+"\n");
            log = log + "WARNING: Saved split files in "+output_dir+" *** but there were "+ errors+" error(s)***\n-- ended at "+ date.getHours()+":"+date.getMinutes()+"\n"+"\n";    
        }
        appendToFile (output_dir+"\\log.txt" ,log);
        return true;
    }
    else
    {
        date = new Date();
        print ("\nERROR: no files were split for \""+in_dir+"\" please check previous messages.\n-- ended at "+ date.getHours()+":"+date.getMinutes());
        log = log + "ERROR: no files split for \""+in_dir+"\" please check previous messages.\n-- ended at "+ date.getHours()+":"+date.getMinutes()+"\n"+"\n";
        appendToFile (output_dir+"\\log.txt" ,log);      
        return false;
    }
}]]>
        </JS_Script>
        <JS_Script name="timeformat">
          
          <![CDATA[// converts the string produced by getInfoResult to an integer
// representing the seconds (truncated)
function TimeString2Int (timestring)
{
    var colons = 0;
    var hours = "";
    var mins = "";
    var secs = "";
    var totaltime = 0;
    if (timestring == "") return 0.0;
    for (i=0;i<timestring.length;i++)
    {
        if (timestring[i] == ":") colons = colons +1;
        else
        {
            if (colons == 0) hours = hours + timestring[i];
            else if (colons == 1) mins = mins + timestring[i];
            else if (colons == 2) secs = secs + timestring[i];
            else break;
        }       
    }
    var totalsecs = (parseFloat(hours) * 3600) + (parseFloat(mins) * 60) + parseFloat(secs);  
    //print ("hours: "+hours+"\nminutes: "+mins+"\nseconds: "+secs);
    return (totalsecs);
}]]>
        </JS_Script>
        <JS_Script name="createDir">
          
          <![CDATA[function splitPath (path) // uses "\\" as path delimiter...
{
    if (path == "")
    {
        return (null);
    }
    var split = path.split ("\\");
    return (split);
}
function createDir (path) // creates dir using makeDir for any depth. use "\\" as path delimiter
{   
    if (existsDir (path)) // dir already exists
    {
        return (false);
    }
    var path_array = splitPath (path);
    var levels = path_array[0];
    for (ipath =0; ipath < path_array.length-1; ipath++)
    {
        levels = levels + "\\"+path_array[ipath+1];
        if (existsDir (levels)) // parial part of path already exists
        {        
        }
        else
        {
            //print (levels);
            makeDir (levels);
        }
    }
    
    if (existsDir (levels)) // non si sa mai...
    {
        return (true);
    }
    else {
        return (false);
    }
}
// uncomment belo to test
/*if (createDir ("c:\\1\\2\\3\\4\\5\\6\\7\\8\\9\\10"))
{
print ("ok");
}
if (createDir ("c:\\1\\2\\3\\4\\5\\6\\7\\8\\9\\10\\11\\12\\13\\14\\15\\16\\17\\18\\19\\20"))
{
print ("ok again");
}*/]]>
        </JS_Script>
        <JS_Script name="getfilelist">
          
          <![CDATA[/* lists the files (only files, no directories) in a directory
with a certain mask
returns an array with the files.
If no file is found it will return an empty array 
*/
function getfilelist (
getflielist_dir,        //directory 
getflielist_mask        // mask e.g. "*.*"
)
{
  var list = new Array();
  if (!existsDir(getflielist_dir))  // check that the directory exists
  {
	return (list)
  }
  var getfilelist_file = getFirstFile(getflielist_dir, getflielist_mask);
  if (getfilelist_file != null)
  {
    list.push (getfilelist_file);
  }
  while (getfilelist_file != null)
  {
     var nextfile = getNextFile();
     if (nextfile == null)
     {
       break;
     }
     list.push (nextfile);
     nextfile = undefined;
    }
  return (list);
}]]>
        </JS_Script>
        <JS_Script name="strip_file">
          
          <![CDATA[// strips just the filename from an URL (or pathname)
// e.g. "http://level1/level2/leveln/file.ext" will return "file.ext"
//      "c:\\mypath\file.ext" will return "file.ext"
function strip_filename (URL)
{
    var file = URL;
      for (i=URL.length-1; i>= 0; i--) {       
         if (URL[i] == "/" || URL[i] == "\\" ) 
         {
             file = file.slice(i+1);
             break;
         }       
      }
    return (file);
}]]>
        </JS_Script>
        <JS_Script name="strip_path">
          
          <![CDATA[// strips just the path  from an URL containing a filename
// (or better strips the last level in path)
// e.g. "http://level1/level2/leveln/file.ext" will return "http://level1/level2/leveln"
//      "c:\\mypath\\file.ext" will return "c:\mypath"
function strip_pathname (URL)
{
    var file = URL;
      for (i=URL.length-1; i>= 0; i--) {       
         if (URL[i] == "/" || URL[i] == "\\" ) 
         {
             file = file.slice(0,i);
             break;
         }       
      }
    return (file);
}
/* test
print (strip_pathname ("c:\\mypath\\file.ext"));
*/]]>
        </JS_Script>
        <JS_Script name="strip_extension">
          
          <![CDATA[/* strips the extension from a filename:
by extension any substring following the last "." char found
is intended
*/
function strip_extension (extesnsion_file)
{
    var no_extension_file = extesnsion_file;
      for (i=extesnsion_file.length-1; i>=0; i--) {       
         if (extesnsion_file[i] == ".") 
         {
             no_extension_file  = no_extension_file .slice(0,i);
             break;
         }       
      }
    return (no_extension_file);
}
/* test 
var files = ("c:\\asdas\\sdsddsd\\aassdas.sss");
print (files);
print (strip_extension (files));
files = ("this.filename.contains.dots.but.only.the.last.is.deleted.ext");
print (files);
print (strip_extension (files));
files = ("c:\\123\\456\\789"); // no extension...
print (files);
print (strip_extension (files));
//*/]]>
        </JS_Script>
        <JS_Script name="number_to_month">
          
          <![CDATA[function number_to_month (month_number)
{
    var the_month_name ="";
    var months = new Array ("January",
                            "February",
                            "March",
                            "April",
                            "May",
                            "June",
                            "July",
                            "August",
                            "September",
                            "October",
                            "November",
                            "December");
    if (month_number >=1 && month_number <=12)
    {
        the_month_name = months [month_number-1];
    }
    return the_month_name;
}]]>
        </JS_Script>
        <JS_Script name="_test">
          
          <![CDATA[split_to_dir (input_dir, out_dir, 0.0, 30.0);]]>
        </JS_Script>
      </Rule_Body>
      <Dependencies>
        <Dependency>
          <Plug_In_name>RingtoneAdaptation</Plug_In_name>
          <Version>1.001</Version>
        </Dependency>
      </Dependencies>
    </AXCP_Rule>
  </Definition>
</Rule>

