%ascii file of all of the SSJ data for a particular day is fileStr
%function fileStr = createCenergyText2(dateVec,sat)
function fileStr = createCenergyText2(dateVec,sat,year)

%The datloc structure will be written out to a file called datalocations.txt,
%which is used by the docenergy.sh shell script. I realize its a clunky way
%of doing things but just imagine passing all of these on the command
%line...I think this is better.

%This should be the ONLY place you need to change locations. Modifying
%datalocations.txt will not do anything since it will be overwritten when
%you call this function.


%Set data locations here
yearS = int2str(year);
    datloc.idm_source_path ='/hao/aim3/dmsp/dmsp_idm_4s/';
    datloc.ssj_binary_path ='/hao/aim3/dmsp/dmsp_rich/dmspssj/';
% Emery cannot make any subdirectories or files in dmspssjtxt which is Liam's directory 
%  fileStr are the names in ~emery/reu11/, but names in txt_dmspssj/yearS/ are sat_yearmoda.txt
    datloc.ssj_daily_path =strcat('/hao/aim3/dmsp/dmsp_rich/txt_dmspssj/',yearS,'/'); %THIS IS THE DESTINATION DIRECTORY FOR CENERGY OUTPUT
     datloc.log_path ='/home/holden/reu12_emery_july20/';
     datloc.script_path ='/home/emery/reu11/';
     datloc.cenergy_path ='/home/holden/reu12_emery_july20/';
     datloc.temp_path ='/home/holden/reu12_emery_july20/';
%    datloc.temp_path =datloc.ssj_daily_path;

    fprintf('Now writing data locations to datalocations.txt in current directory.\n');
    writeDataLocationsFile(datloc);
    
%Generate the configuration file used by cenergy.pro
generateConfigFile('config.txt');

%This parses the dateVec into some sensibly named variables
    year = dateVec(1); yearS = int2str(year);
    month = dateVec(2); monthS = sprintf('%2.2d',month);
    day = dateVec(3); dayS = sprintf('%2.2d',day);
    daynumber = dayno([year,month,day,0,0,0]);
    satS = int2str(sat);
    
%This creates the files names for passing to docenergy.sh    
    fileStr = strcat('cenergy_all_f',satS,'_',yearS,monthS,dayS,'.txt');
    logStr = strcat(datloc.log_path,'cenergy_f',satS,'_',yearS,monthS,dayS,'_full.log');
    lastdayswitch=lastDayCheck(year, daynumber);
    
%This creates the command that will be run at the unix prompt  
    cmd = sprintf('%sdocenergy2.sh %i %i %i %i %i %i config.txt',datloc.script_path, ...
        year, month, day, daynumber, sat, lastdayswitch);
    
    disp(cmd);
%This executes the command stored in cmd    
    exitstat = system(cmd);
    
%This is an error check    
    if (exitstat ~= 0)
        fprintf('Shell script exited with non-zero status check.\n Check log at %s.\n',logStr);
    end 

%This clears a temporary file    
    fprintf('Cleaning up...\n');
    exitstat = system('rm config.txt');
    if (exitstat ~= 0)
        fprintf('Failed to remove config.txt.\n');
    end 
end

function writeDataLocationsFile(datlocStruct)
    %Function which simply writes the structure to a file in the following
    %manner:
    %Name of structure field<space>Value of structure field
    %Only works for 1-d structures
    
    fid = fopen('datalocations.txt','w');
    datlocFields = fieldnames(datlocStruct);
    datlocCellArr = struct2cell(datlocStruct);
    
    for j = 1:length(datlocFields)
        
        fprintf(fid,'%s %s\n',datlocFields{j},datlocCellArr{j});
        
    end
    
    fclose(fid)
end

function generateConfigFile(filename)
%This little gem of a function generates the configuration file that cenergy.pro needs and docenergy2.sh modifies.
%This is utter and complete hackery, but it was quicker that porting
%docenergy2.sh or cenergy.pro into MATLAB
fid = fopen(filename,'w');
    fprintf(fid,'-1                               ; 1=ps 2=tek 3=x -3=win\n');
    fprintf(fid,'0                               ; 0=standard postscript, 1=encapsulated PS\n');
    fprintf(fid,'f15.ps\n')
    fprintf(fid,'/hao/aim3/dmsp/dmsp_rich/dmspssj/j1396/j4f1396003\n')
    fprintf(fid,'0                               ; Background removal, 0=No, NE 0 = Yes\n')
    fprintf(fid,'3                               ; 1=DM data, 2=SSM data, 3=Ni 4=DM/M/Ni\n')
    fprintf(fid,'p                               ; l=landscape, p=protrait mode for PS file\n')
    fprintf(fid,'E                               ; N=Diff Number Flux E=Diff Energy Flux\n')
    fprintf(fid,'E                               ; N=Integrated Num Flux E=Integrated EnergyFlux\n')
    fprintf(fid,'1996                            ; Year\n')
    fprintf(fid,'01                              ; Month\n')
    fprintf(fid,'03                              ; Day\n')
    fprintf(fid,'0000                            ; Start time HHMM\n')
    fprintf(fid,'2359                            ; End Time HHMM\n')
    fprintf(fid,'30                              ; Minutes/page (program limit is 30 min)\n')
    fprintf(fid,'45.                             ; Min Lat\n')
    fprintf(fid,'3                               ; 3=Both Hemi 1=North 2=South\n')
    fprintf(fid,'13                              ; Sat number\n')
    fprintf(fid,'y                               ; y=color n=Gray scale\n')
    fprintf(fid,'n                               ; y=filter Eflux and AvgE\n')
    fprintf(fid,'n                               ; y=ion spectrogram upside down\n')
    fprintf(fid,'n                               ; n=no lines on plot\n')
    fclose(fid)
end
    
function out = dayno(datevec)
%lmk - Expects date vector format [YYYY MM DD 0 0 0]
dateNum = datenum(datevec)-datenum([datevec(1) 1 1 0 0 0]) + 1;
out = dateNum;
end

function yesno = lastDayCheck(year, daynum)
    if ((mod(year,4) == 0)) %leap year
        switch daynum 
            case {31,60,91,121,152,182,213,244,274,305,335,366} 
                yesno = 1;
            otherwise
                yesno = 0;
        end
    else %non-leap year
        switch daynum 
            case{31,59,90,120,151,181,212,243,273,304,334,365}
                yesno = 1;
            otherwise
                yesno = 0;
        end
    end
end

       
