// TaskSchedulerHelper2Dlg.cpp : 実装ファイル
//

#include "stdafx.h"
#include "TaskSchedulerHelper2.h"
#include "TaskSchedulerHelper2Dlg.h"
#include <initguid.h>
#include <mstask.h>
#include <shlwapi.h>
#include <locale.h>
#include "NameInputDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

#if 1
#define Wcscpy_s(d,n,s) wcsncpy_s((d),-1,(s),(n)-1)
#define Wcscat_s(d,n,s) wcsncat_s((d),-1,(s),(n)-1)
#define Wcsncpy_s(d,m,s,n) wcsncpy_s((d),-1,(s),((n)>=(m))?(m)-1:(n))
#else
#define Wcscpy_s wcscpy_s
#define Wcscat_s wcscat_s
#define Wcsncpy_s wcsncpy_s
#endif

// CTaskSchedulerHelper2Dlg ダイアログ

#pragma warning ( disable : 4996 )


CTaskSchedulerHelper2Dlg::CTaskSchedulerHelper2Dlg(CWnd* pParent /*=NULL*/)
	: CDialog(CTaskSchedulerHelper2Dlg::IDD, pParent)
	, opt_number(0)
	, channel_number(0)
	, strCapsts(_T(""))
	, strFoldername(_T(""))
	, strFilename(_T("test"))
	, strChannel(_T(""))
	, strId(_T(""))
	, strCommandline(_T(""))
	, strVlcParam(_T(""))
	, bPowerOn(FALSE)
	, bPowerOff(FALSE)
	, bBcs(FALSE)
	, bB25(FALSE)
	, bSel(FALSE)
	, bSus(FALSE)
	, bVlc(FALSE)
	, strTaskName(_T(""))
	, nTaskType(0)
	, bDelTask(FALSE)
	, bResume(FALSE)
	, strAccount(_T(""))
	, strPass1(_T(""))
	, strPass2(_T(""))
	, bAutoClose(FALSE)
	, bParentheses(FALSE)
	///
	, bRmc(FALSE)
	, bSubtitle(TRUE)
	, strFileExt(_T(".ts"))
	, s_title(_T("test"))
	, s_subtitle(_T("test"))
	, bExtend(FALSE)
	, bForceSet(FALSE)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	wFilename[0] = L'\0';
	wParameter[0] = L'\0';
	selWeek = -1;
	for ( int n = 0; n < 7; n++ ) bWeek[n] = FALSE;///2.1
}

void CTaskSchedulerHelper2Dlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_CHANNEL_LIST, ctrlChannelList);
	DDX_Control(pDX, IDC_START_PICKER, ctrlDateTime1);
	DDX_Control(pDX, IDC_END_PICKER, ctrlDateTime2);
	DDX_Control(pDX, IDC_MONTHCALENDAR, ctrlCal);
	DDX_Control(pDX, IDC_OPTION_TAB, ctrlOptTab);
	DDX_Text(pDX, IDC_CAPSTS_EDIT, strCapsts);
	DDX_Text(pDX, IDC_FOLDER_EDIT, strFoldername);
	DDX_Text(pDX, IDC_FILENAME_EDIT, strFilename);
	DDX_Text(pDX, IDC_FILEEXT_EDIT, strFileExt);
	DDX_Text(pDX, IDC_CHANNEL_EDIT, strChannel);
	DDX_Text(pDX, IDC_ID_EDIT, strId);
	DDX_Text(pDX, IDC_COMMANDLINE_EDIT, strCommandline);
	//	DDX_Text(pDX, IDC_VLC_PARAM_EDIT, strVlcParam);
	DDX_Check(pDX, IDC_PON_CHECK, bPowerOn);
	DDX_Check(pDX, IDC_POFF_CHECK, bPowerOff);
	//	DDX_Check(pDX, IDC_BCS_CHECK, bBcs);
	DDX_Check(pDX, IDC_B25_CHECK, bB25);
	DDX_Check(pDX, IDC_SEL_CHECK, bSel);
	//	DDX_Check(pDX, IDC_SUSPEND_CHECK, bSus);
	DDX_Check(pDX, IDC_VLCREC_CHECK, bVlc);
	DDX_Check(pDX, IDC_RMC_CHECK, bRmc);
	DDX_Check(pDX, IDC_SUBTITLE_CHECK, bSubtitle);
	DDX_Check(pDX, IDC_EXTEND_CHECK, bExtend);
	DDX_Text(pDX, IDC_TASK_NAME_EDIT, strTaskName);
	DDX_Radio(pDX, IDC_TASK_RADIO1, nTaskType);
	DDX_Check(pDX, IDC_DEL_CHECK, bDelTask);
	DDX_Check(pDX, IDC_RESUME_CHECK, bResume);
	DDX_Text(pDX, IDC_TASK_ACCOUNT_EDIT, strAccount);
	DDX_Text(pDX, IDC_TASK_PASS_EDIT1, strPass1);
	DDX_Text(pDX, IDC_TASK_PASS_EDIT2, strPass2);
	DDX_Check(pDX, IDC_AUTO_CLOSE_CHECK, bAutoClose);
	DDX_Check(pDX, IDC_PARENTHESES_CHECK, bParentheses);
	DDX_Check(pDX, IDC_FORCE_SET_CHECK, bForceSet);
	DDX_Control(pDX, IDC_COMBO_ENCODE, m_ComboEncode);
	DDX_Check(pDX, IDC_WEEK_0, bWeek[0]);
	DDX_Check(pDX, IDC_WEEK_1, bWeek[1]);
	DDX_Check(pDX, IDC_WEEK_2, bWeek[2]);
	DDX_Check(pDX, IDC_WEEK_3, bWeek[3]);
	DDX_Check(pDX, IDC_WEEK_4, bWeek[4]);
	DDX_Check(pDX, IDC_WEEK_5, bWeek[5]);
	DDX_Check(pDX, IDC_WEEK_6, bWeek[6]);
}

BEGIN_MESSAGE_MAP(CTaskSchedulerHelper2Dlg, CDialog)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDOK, &CTaskSchedulerHelper2Dlg::OnBnClickedOk)
	ON_BN_CLICKED(IDCANCEL, &CTaskSchedulerHelper2Dlg::OnBnClickedCancel)
	ON_WM_CLOSE()
	ON_BN_CLICKED(IDC_PON_CHECK, &CTaskSchedulerHelper2Dlg::ChangeOptions)
	ON_BN_CLICKED(IDC_POFF_CHECK, &CTaskSchedulerHelper2Dlg::ChangeOptions)
//	ON_BN_CLICKED(IDC_BCS_CHECK, &CTaskSchedulerHelper2Dlg::ChangeOptions)
	ON_BN_CLICKED(IDC_B25_CHECK, &CTaskSchedulerHelper2Dlg::ChangeOptions)
	ON_BN_CLICKED(IDC_SEL_CHECK, &CTaskSchedulerHelper2Dlg::ChangeOptions)
//	ON_BN_CLICKED(IDC_SUSPEND_CHECK, &CTaskSchedulerHelper2Dlg::ChangeOptions)
	ON_BN_CLICKED(IDC_VLCREC_CHECK, &CTaskSchedulerHelper2Dlg::ChangeOptions)
	ON_EN_CHANGE(IDC_CAPSTS_EDIT, &CTaskSchedulerHelper2Dlg::ChangeOptions)
	ON_EN_CHANGE(IDC_FOLDER_EDIT, &CTaskSchedulerHelper2Dlg::ChangeOptions)
	ON_EN_CHANGE(IDC_FILENAME_EDIT, &CTaskSchedulerHelper2Dlg::ChangeOptions)
	ON_EN_CHANGE(IDC_FILEEXT_EDIT, &CTaskSchedulerHelper2Dlg::ChangeOptions)
	ON_EN_CHANGE(IDC_CHANNEL_EDIT, &CTaskSchedulerHelper2Dlg::ChangeOptions)
	ON_BN_CLICKED(IDC_RMC_CHECK, &CTaskSchedulerHelper2Dlg::ChangeOptions)
	ON_EN_CHANGE(IDC_ID_EDIT, &CTaskSchedulerHelper2Dlg::ChangeOptions)
//	ON_EN_CHANGE(IDC_VLC_PARAM_EDIT, &CTaskSchedulerHelper2Dlg::ChangeOptions)
	ON_NOTIFY(DTN_DATETIMECHANGE, IDC_START_PICKER, &CTaskSchedulerHelper2Dlg::OnDtnDatetimechangePicker)
	ON_NOTIFY(DTN_DATETIMECHANGE, IDC_END_PICKER, &CTaskSchedulerHelper2Dlg::OnDtnDatetimechangePicker)
	ON_BN_CLICKED(IDC_CAPSTS_BUTTON, &CTaskSchedulerHelper2Dlg::OnBnClickedCapstsButton)
	ON_BN_CLICKED(IDC_FOLDER_BUTTON, &CTaskSchedulerHelper2Dlg::OnBnClickedFolderButton)
	ON_BN_CLICKED(IDC_TASK_SET_BUTTON, &CTaskSchedulerHelper2Dlg::OnBnClickedTaskSetButton)
	ON_BN_CLICKED(IDC_EPG_BUTTON, &CTaskSchedulerHelper2Dlg::OnBnClickedEpgButton)
	ON_BN_CLICKED(IDC_EXTEND_CHECK, &CTaskSchedulerHelper2Dlg::OnBnClickedExtendCheck)
	ON_NOTIFY(UDN_DELTAPOS, IDC_ID_SPIN, &CTaskSchedulerHelper2Dlg::OnDeltaposIdSpin)
	ON_LBN_SELCHANGE(IDC_CHANNEL_LIST, &CTaskSchedulerHelper2Dlg::OnLbnSelchangeChannelList)
	ON_NOTIFY(TCN_SELCHANGING, IDC_OPTION_TAB, &CTaskSchedulerHelper2Dlg::OnTcnSelchangingOptionTab)
	ON_NOTIFY(TCN_SELCHANGE, IDC_OPTION_TAB, &CTaskSchedulerHelper2Dlg::OnTcnSelchangeOptionTab)
	ON_BN_CLICKED(IDC_ADD_OPTION_BUTTON, &CTaskSchedulerHelper2Dlg::OnBnClickedAddOptionButton)
	ON_BN_CLICKED(IDC_DEL_OPTION_BUTTON, &CTaskSchedulerHelper2Dlg::OnBnClickedDelOptionButton)
	ON_BN_CLICKED(IDC_TASKVIEWER_BUTTON, &CTaskSchedulerHelper2Dlg::OnBnClickedTaskviewerButton)
	ON_BN_CLICKED(IDC_FORCE_SET_CHECK, &CTaskSchedulerHelper2Dlg::ChangeOptions)
	ON_BN_CLICKED(IDC_SUBTITLE_CHECK, &CTaskSchedulerHelper2Dlg::OnBnClickedSubtitleCheck)
	ON_BN_CLICKED(IDC_PARENTHESES_CHECK, &CTaskSchedulerHelper2Dlg::OnBnClickedParenthesesCheck)
	ON_CBN_CLOSEUP(IDC_COMBO_ENCODE, &CTaskSchedulerHelper2Dlg::OnCbnCloseupComboEncode)
	ON_NOTIFY(MCN_SELECT, IDC_MONTHCALENDAR, &CTaskSchedulerHelper2Dlg::OnMcnSelectMonthcalendar)
	ON_BN_CLICKED(IDC_WEEK_0, &CTaskSchedulerHelper2Dlg::OnBnClickedWeek)
	ON_BN_CLICKED(IDC_WEEK_1, &CTaskSchedulerHelper2Dlg::OnBnClickedWeek)
	ON_BN_CLICKED(IDC_WEEK_2, &CTaskSchedulerHelper2Dlg::OnBnClickedWeek)
	ON_BN_CLICKED(IDC_WEEK_3, &CTaskSchedulerHelper2Dlg::OnBnClickedWeek)
	ON_BN_CLICKED(IDC_WEEK_4, &CTaskSchedulerHelper2Dlg::OnBnClickedWeek)
	ON_BN_CLICKED(IDC_WEEK_5, &CTaskSchedulerHelper2Dlg::OnBnClickedWeek)
	ON_BN_CLICKED(IDC_WEEK_6, &CTaskSchedulerHelper2Dlg::OnBnClickedWeek)
END_MESSAGE_MAP()


// CTaskSchedulerHelper2Dlg メッセージ ハンドラ

BOOL CTaskSchedulerHelper2Dlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// このダイアログのアイコンを設定します。アプリケーションのメイン ウィンドウがダイアログでない場合、
	//  Framework は、この設定を自動的に行います。
	SetIcon(m_hIcon, TRUE);			// 大きいアイコンの設定
	SetIcon(m_hIcon, FALSE);		// 小さいアイコンの設定

	// TODO: 初期化をここに追加します。
	LoadChannelFile();
	for(int i = 0; i < channel_number; i++){
		ctrlChannelList.AddString(channel[i].name);
		if(wcsstr(channel[i].command, strChannel) != NULL) ctrlChannelList.SetCurSel(i);
	}

	LoadIniFile();
	SetOptions(ctrlOptTab.GetCurSel());

	ctrlDateTime1.SetFormat(L"HH:mm");
	ctrlDateTime2.SetFormat(L"HH:mm");
	ctrlDateTime2.GetTime(endt[0]);///
	ctrlDateTime2.GetTime(endt[1]);///
	OnMcnSelectMonthcalendar(NULL,NULL);///2.1

#if 1 ///2.1
	nAuto = 0;
	wchar_t *wp = cmdline;//L"-auto test.tvpi";
	if( wp ) while ( *wp ) {
		if ( wp[0] != L'-' ) {
			wchar_t epg_file_path[256];
			if(wp[0] != '"'){
				Wcscpy_s(epg_file_path, 256, wp);
			}else{
				Wcsncpy_s(epg_file_path, 256, wp + 1, wcslen(wp) -2);
			}
			EPG epg;
			if(OpenEPGFile(epg_file_path, &epg)){
				SetEPG(&epg);
			}
			else {
				nAuto = 0;///EPGファイルが開けない場合は無効.
			}
			break;///EPGファイル名は最後.
		}
		else {
			if ( wp[1] == L'a' ) {//"-auto[0|1]"
				nAuto = (wp[5] == L'1') ? 2 : 1;
				wp += 6;
			}
		}
		
		while ( *wp == L' ' ) wp++;
		if ( !*wp ) {
			nAuto = 0;///EPGファイル名指定が無い場合は無効.
			break;
		}
	}
#else
	if(wcslen(cmdline) > 0){
		wchar_t epg_file_path[256];
		if(cmdline[0] != '"'){
			Wcscpy_s(epg_file_path, 256, cmdline);
		}else{
			Wcsncpy_s(epg_file_path, 256, &cmdline[1], wcslen(cmdline) -2);
		}
		EPG epg;
		if(OpenEPGFile(epg_file_path, &epg)){
			SetEPG(&epg);
		}
	}
#endif
	OpenSeaIni();
	m_ComboEncode.SetCurSel(m_ComboEncode.FindString(0,(LPCTSTR)strVlcParam));

	MakeCommandline();

	return TRUE;  // フォーカスをコントロールに設定した場合を除き、TRUE を返します。
}

// ダイアログに最小化ボタンを追加する場合、アイコンを描画するための
//  下のコードが必要です。ドキュメント/ビュー モデルを使う MFC アプリケーションの場合、
//  これは、Framework によって自動的に設定されます。

void CTaskSchedulerHelper2Dlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 描画のデバイス コンテキスト

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// クライアントの四角形領域内の中央
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// アイコンの描画
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
	
	if ( nAuto == 1 ) {///2.1
		nAuto = 3;
		OnBnClickedTaskSetButton();
	}
}

// ユーザーが最小化したウィンドウをドラッグしているときに表示するカーソルを取得するために、
//  システムがこの関数を呼び出します。
HCURSOR CTaskSchedulerHelper2Dlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

void CTaskSchedulerHelper2Dlg::OnClose()
{
	SaveIniFile();

	EndDialog(0);
	CDialog::OnClose();
}

void CTaskSchedulerHelper2Dlg::OnBnClickedCapstsButton()
{
	UpdateData(TRUE);

	wchar_t wFilename[WCHAR_MAX];
	Wcscpy_s(&wFilename[0], WCHAR_MAX, L"cap_sts.exe");

	OPENFILENAME ofn;
	memset(&ofn, 0, sizeof(ofn));
	ofn.lStructSize = sizeof(ofn);
	ofn.lpstrFilter = L"実行ファイル\0*.exe;*.bat\0全てのファイル\0*.*\0\0";
	ofn.lpstrFile = wFilename;
	ofn.nMaxFile = WCHAR_MAX;
	ofn.lpstrDefExt = L"exe";
	ofn.Flags = OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR;

	if( GetOpenFileNameW(&ofn) != TRUE) return;

	strCapsts = wFilename;

	GetOptions();
	MakeCommandline();
}

void CTaskSchedulerHelper2Dlg::MakeCommandline(void)
{
	CString strTemp;
	wchar_t *end;

	Wcscpy_s(wFilename, 256, strCapsts);

	strTemp.Format(_T("\"%s\\%s%s\""), strFoldername, strFilename, strFileExt);
	Wcscpy_s(wParameter, 256, strTemp);

	if(wcstod(strId, &end) != 0){
		Wcscat_s(wParameter, 256, L" I"+strId);
		if(bRmc){
			Wcscat_s(wParameter, 256, L" R");
			Wcscat_s(wParameter, 256, (!strId[0] ? L"0" : strId));
		}
	}

	Wcscat_s(wParameter, 256, L" @"+strChannel);

	CTime StartTime, EndTime;
	ctrlDateTime1.GetTime(StartTime);
	ctrlDateTime2.GetTime(EndTime);
	wchar_t temp[256];
	swprintf_s(temp, L" %0.2u:%0.2u-%0.2u:%0.2u", StartTime.GetHour(), StartTime.GetMinute(), EndTime.GetHour(), EndTime.GetMinute());
	Wcscat_s(wParameter, 256, temp);

	if(bVlc){
		Wcscat_s(wParameter, 256, L" ");
		Wcscat_s(wParameter, 256, strVlcParam);
	}
	if(bPowerOn) Wcscat_s(wParameter, 256, L" P");
	if(bPowerOff) Wcscat_s(wParameter, 256, L" POFF");
//	if(bBcs)Wcscat_s(wParameter, 256,  L" B");
	if(bB25) Wcscat_s(wParameter, 256, L" B");
	if(bSel) Wcscat_s(wParameter, 256, L" SEL");
	if(bSus) Wcscat_s(wParameter, 256, L" SUSPEND");

	//'?'をFX2IDに変更{
	while ( (end = wcschr(wFilename, L'?')) != NULL ) {//変数endは使いまわし/
		*end = !strId[0] ? L'0' : strId[0];
	}
	while ( (end = wcschr(wParameter, L'?')) != NULL ) {//変数endは使いまわし/
		*end = !strId[0] ? L'0' : strId[0];
	}
	///}

	strCommandline = wFilename;
	strCommandline += " ";
	strCommandline += wParameter;

	UpdateData(	FALSE);

}

void CTaskSchedulerHelper2Dlg::ChangeOptions()
{
	UpdateData(TRUE);
	if(m_ComboEncode.GetCurSel() >= 0){
		m_ComboEncode.GetLBText( m_ComboEncode.GetCurSel(),strVlcParam );
	}

	GetOptions();
	MakeCommandline();
}

void CTaskSchedulerHelper2Dlg::SetOptions(int num)
{
	if((num < 0)||(num >= opt_number)) return;

	strCapsts		= opt[num].Capsts;
	strFoldername	= opt[num].Foldername;
	strFileExt		= opt[num].FileExt;
	strId			= opt[num].Id;
	strVlcParam		= opt[num].VlcParam;

	bPowerOn	= opt[num].PowerOn;
	bPowerOff	= opt[num].PowerOff;
	bBcs		= opt[num].Bcs;
	bB25		= opt[num].B25;
	bSel		= opt[num].Sel;
	bSus		= opt[num].Sus;
	bVlc		= opt[num].Vlc;
	bRmc		= opt[num].Rmc;
}

void CTaskSchedulerHelper2Dlg::GetOptions(void)
{
	int num = ctrlOptTab.GetCurSel();
	
	Wcscpy_s(opt[num].Capsts,		256, strCapsts);
	Wcscpy_s(opt[num].Foldername,	256, strFoldername);
	Wcscpy_s(opt[num].FileExt,		10, strFileExt);
	Wcscpy_s(opt[num].Id,			10, strId);
	Wcscpy_s(opt[num].VlcParam,		30,	strVlcParam);

	opt[num].PowerOn	= bPowerOn;
	opt[num].PowerOff	= bPowerOff;
	opt[num].Bcs		= bBcs;
	opt[num].B25		= bB25;
	opt[num].Sel		= bSel;
	opt[num].Sus		= bSus;
	opt[num].Vlc		= bVlc;
	opt[num].Rmc		= bRmc;
}

void CTaskSchedulerHelper2Dlg::OnDtnDatetimechangePicker(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMDATETIMECHANGE pDTChange = reinterpret_cast<LPNMDATETIMECHANGE>(pNMHDR);
	UpdateData(TRUE);
	MakeCommandline();
	*pResult = 0;
}

void CTaskSchedulerHelper2Dlg::OnBnClickedFolderButton()
{
	UpdateData(TRUE);

	wchar_t wFoldername[WCHAR_MAX];
	Wcscpy_s(&wFoldername[0], WCHAR_MAX, strFoldername);

	LPMALLOC pMalloc;
	//　IMallocインターフェイスへのポインタを取得します。
	if( ::SHGetMalloc( &pMalloc ) != NOERROR )
	return ;

	LPITEMIDLIST pidlRoot, pidlBrowse;
	::SHGetSpecialFolderLocation(this->GetSafeHwnd(), CSIDL_DRIVES, &pidlRoot);
	BROWSEINFO bi;
	::ZeroMemory(&bi, sizeof(BROWSEINFO));
	bi.hwndOwner = this->GetSafeHwnd();
	bi.pidlRoot = pidlRoot; // NULL の時マイコンピュータから表示
	bi.pszDisplayName = wFoldername;
	bi.lpszTitle = L"フォルダを選択してください";
	bi.ulFlags = BIF_RETURNONLYFSDIRS;
	bi.lpfn = NULL;
	//bi.lParam
	//bi.iImage

	pidlBrowse = ::SHBrowseForFolder(&bi);
	if(pidlBrowse) {
		::SHGetPathFromIDList(pidlBrowse, wFoldername);
		strFoldername = wFoldername;
	}
	if( pidlRoot != NULL )
		pMalloc->Free( pidlRoot );
	if( pidlBrowse != NULL )
		pMalloc->Free( pidlBrowse );
	pMalloc->Release();

	GetOptions();
	MakeCommandline();
}

#define TASKS_TO_RETRIEVE          5
void CTaskSchedulerHelper2Dlg::OnBnClickedTaskSetButton()
{
	UpdateData(TRUE);
	if(strTaskName.GetLength() == 0){
		AfxMessageBox(L"設定名を入力してください");
		return;
	}
	if(strAccount.GetLength() == 0){
		AfxMessageBox(L"実行するアカウントを入力してください");
		return;
	}

	if(strPass1 != strPass2){
		AfxMessageBox(L"パスワードが間違っています");
		return;
	}

	HRESULT hr = S_OK;
	ITaskScheduler *pITS;

	hr = CoInitialize(NULL);
	if (SUCCEEDED(hr)){
		hr = CoCreateInstance(CLSID_CTaskScheduler, NULL, CLSCTX_INPROC_SERVER, IID_ITaskScheduler, (void **) &pITS);
		if (FAILED(hr)){
			CoUninitialize();
			AfxMessageBox(L"オブジェクトの作成に失敗しました");
			return;
		}
	}else{
		AfxMessageBox(L"COM初期化エラー");
		return;
	}

	IEnumWorkItems *pIEnum;
	hr = pITS->Enum(&pIEnum);
	if (FAILED(hr)){
		CoUninitialize();
		AfxMessageBox(L"IEnumWorkItemsエラー");
		return;
	}
	wchar_t temp[256];
	Wcscpy_s(temp, 256, strTaskName.GetString());

	///禁止文字チェック{
	if (
	(wcschr(temp, L'\\') != NULL) ||
	(wcschr(temp, L'/' ) != NULL) ||
	(wcschr(temp, L':' ) != NULL) ||
	(wcschr(temp, L'*' ) != NULL) ||
	(wcschr(temp, L'?' ) != NULL) ||
	(wcschr(temp, L'\"') != NULL) ||
	(wcschr(temp, L'<' ) != NULL) ||
	(wcschr(temp, L'>' ) != NULL) ||
	(wcschr(temp, L'|' ) != NULL) ||
	(wcschr(strFilename, L'\\') != NULL) ||
	(wcschr(strFilename, L'/' ) != NULL) ||
	(wcschr(strFilename, L':' ) != NULL) ||
	(wcschr(strFilename, L'*' ) != NULL) ||
	(wcschr(strFilename, L'?' ) != NULL) ||
	(wcschr(strFilename, L'\"') != NULL) ||
	(wcschr(strFilename, L'<' ) != NULL) ||
	(wcschr(strFilename, L'>' ) != NULL) ||
	(wcschr(strFilename, L'|' ) != NULL) ) {
		AfxMessageBox(L"禁止文字(\\/:*?\"<>|)があります\r\n名前を修正してください");
		return;
	}
	///}

	///>
	if ( bForceSet ) {
		char tn[512],cmd[512];
		char *s = tn;
		wchar_t *t = temp;
		wcstombs(s, t, 512);
		sprintf(cmd,"schtasks /delete /f /tn \"%s\"", tn);
		system(cmd);
	}
	///<
	Wcscat_s(temp, 256, L".job");

	LPWSTR *lpwszNames;
	DWORD dwFetchedTasks = 0;
	while (SUCCEEDED(pIEnum->Next(TASKS_TO_RETRIEVE, &lpwszNames, &dwFetchedTasks)) && (dwFetchedTasks != 0)){
		while (dwFetchedTasks){
			if(wcscmp(lpwszNames[--dwFetchedTasks], temp) == 0){
				AfxMessageBox(L"既に同じ登録名があります\r\n違う登録名を入力してください");
				return;
			}
			CoTaskMemFree(lpwszNames[dwFetchedTasks]);
		}
		CoTaskMemFree(lpwszNames);
	}
	pIEnum->Release();

	ITask *pITask;
	IPersistFile *pIPersistFile;
	hr = pITS->NewWorkItem(strTaskName, CLSID_CTask, IID_ITask, (IUnknown**)&pITask);
	if (FAILED(hr)){
		if ( pITask ) pITask->Release(); ///2.1 bugfix. NULL pointer accessed.
		CoUninitialize();
		AfxMessageBox(L"新しいタスクアイテムをメモリに作成できません");
		return;
	}

	hr = pITask->SetAccountInformation(strAccount.GetString(), strPass1.GetString());
	if (FAILED(hr)){
		pITask->Release();
		CoUninitialize();
		AfxMessageBox(L"アカウントとパスワードが設定できません");
		return;
	}

	hr = pITask->SetApplicationName(wFilename);
	if (FAILED(hr)){
		pITask->Release();
		CoUninitialize();
		AfxMessageBox(L"ApplicationName(cap_sts)が設定できません");
		return;
	}

//	wchar_t *p = wcsrchr(wFilename, L'\\');
//	wchar_t path[256];
//	Wcsncpy_s(path, 256, wFilename, p - &wFilename[0]);
//	hr = pITask->SetWorkingDirectory(path);
	hr = pITask->SetWorkingDirectory(strFoldername);

	hr = pITask->SetParameters(wParameter);
	if (FAILED(hr)){
		pITask->Release();
		CoUninitialize();
		AfxMessageBox(L"コマンドラインパラメータが設定できません");
		return;
	}

	// ここからトリガー設定
	ITaskTrigger *pITaskTrigger;
	WORD piNewTrigger;
	hr = pITask->CreateTrigger(&piNewTrigger, &pITaskTrigger);
	if (FAILED(hr)){
		pITask->Release();
		CoUninitialize();
		AfxMessageBox(L"タスクの実行開始トリガを新しく作成できません");
		return;
	}

	TASK_TRIGGER pTrigger;
	ZeroMemory(&pTrigger, sizeof (TASK_TRIGGER));

	struct tm date;
	CTime SetTimeTmp;
	ctrlDateTime1.GetTime(SetTimeTmp);
	
	date.tm_isdst = -1;
	date.tm_sec  = 0;
	date.tm_min  = SetTimeTmp.GetMinute();
	date.tm_hour = SetTimeTmp.GetHour();
	ctrlCal.GetCurSel(SetTimeTmp);
	date.tm_mday = SetTimeTmp.GetDay();
	date.tm_mon  = SetTimeTmp.GetMonth() - 1;
	date.tm_year = SetTimeTmp.GetYear() - 1900;
	
	time_t timer = mktime(&date) - (time_t)60;//一分前/
	localtime_s(&date, &timer);
	
	CTime SetTime(date.tm_year + 1900 ,date.tm_mon + 1 ,date.tm_mday ,date.tm_hour ,date.tm_min , 0);

	pTrigger.wStartHour = SetTime.GetHour();
	pTrigger.wStartMinute = SetTime.GetMinute();
	pTrigger.wBeginDay = SetTime.GetDay();
	pTrigger.wBeginMonth = SetTime.GetMonth();
	pTrigger.wBeginYear = SetTime.GetYear();
	pTrigger.cbTriggerSize = sizeof(TASK_TRIGGER);

	DWORD flag = TASK_FLAG_RUN_ONLY_IF_LOGGED_ON;
	if(bDelTask) flag |= TASK_FLAG_DELETE_WHEN_DONE;
	if(bResume) flag |= TASK_FLAG_SYSTEM_REQUIRED;
	hr = pITask->SetFlags(flag);
	if (FAILED(hr)){
		pITask->Release();
		CoUninitialize();
		AfxMessageBox(L"タスクフラグが設定できません");
		return;
	}

	switch(nTaskType){
		case 0:
			pTrigger.TriggerType = TASK_TIME_TRIGGER_ONCE;
			break;
		case 1:
			pTrigger.TriggerType = TASK_TIME_TRIGGER_DAILY;
			pTrigger.Type.Daily.DaysInterval = 1;
			break;
		case 2:
			pTrigger.TriggerType = TASK_TIME_TRIGGER_WEEKLY;
			pTrigger.Type.Weekly.WeeksInterval = 1;
			
///2.1>
#if 1
			{//SetTime.GetDayOfWeek()でなくIDC_WEEK CheckBoxを使用するので、23:59(00:00-1min)ではローテイトする.
				int ofs = ((SetTime.GetHour()==23) && (SetTime.GetMinute()==59)) ? 1 : 0;
				pTrigger.Type.Weekly.rgfDaysOfTheWeek = 0;
				bWeek[7] = bWeek[0];
				for ( int n = 0; n < 7; n++ ) {
					if ( bWeek[ofs + n] ) pTrigger.Type.Weekly.rgfDaysOfTheWeek |= 0x80;
					pTrigger.Type.Weekly.rgfDaysOfTheWeek >>= 1;
				}
			}
#else
			switch(SetTime.GetDayOfWeek()){
				case 1:
					pTrigger.Type.Weekly.rgfDaysOfTheWeek = TASK_SUNDAY;
					break;
				case 2:
					pTrigger.Type.Weekly.rgfDaysOfTheWeek = TASK_MONDAY;
					break;
				case 3:
					pTrigger.Type.Weekly.rgfDaysOfTheWeek = TASK_TUESDAY;
					break;
				case 4:
					pTrigger.Type.Weekly.rgfDaysOfTheWeek = TASK_WEDNESDAY;
					break;
				case 5:
					pTrigger.Type.Weekly.rgfDaysOfTheWeek = TASK_THURSDAY;
					break;
				case 6:
					pTrigger.Type.Weekly.rgfDaysOfTheWeek = TASK_FRIDAY;
					break;
				case 7:
					pTrigger.Type.Weekly.rgfDaysOfTheWeek = TASK_SATURDAY;
					break;
				default:
					pTrigger.Type.Weekly.rgfDaysOfTheWeek = TASK_SUNDAY;
					break;
			}
#endif
///2.1<
			pTrigger.rgFlags = TASK_FLAG_RESTART_ON_IDLE_RESUME | TASK_FLAG_RUN_ONLY_IF_LOGGED_ON;
			break;
		default:
			pTrigger.TriggerType = TASK_TIME_TRIGGER_ONCE;
			break;
	}

	hr = pITaskTrigger->SetTrigger (&pTrigger);
	if (FAILED(hr))
	{
		pITask->Release();
		pITaskTrigger->Release();
		CoUninitialize();
		AfxMessageBox(L"タスクの実行開始トリガをセットできません");
		return;
	}

	pITS->Release();
	if (FAILED(hr)){
		CoUninitialize();
		AfxMessageBox(L"pITSリリース失敗");
		return;
	}

	hr = pITask->QueryInterface(IID_IPersistFile, (void **)&pIPersistFile);

	pITask->Release();
	if (FAILED(hr)){
		CoUninitialize();
		AfxMessageBox(L"pITaskリリース失敗");
		return;
	}

	hr = pIPersistFile->Save(NULL, TRUE);
	pIPersistFile->Release();
	if (FAILED(hr)){
		CoUninitialize();
		AfxMessageBox(L"pIPersistFile->Save失敗");
		return;
	}
	if ( !nAuto )AfxMessageBox(L"登録しました");///2.1
	if(bAutoClose || (nAuto == 3)) CTaskSchedulerHelper2Dlg::OnClose();///2.1
}

void CTaskSchedulerHelper2Dlg::OnBnClickedEpgButton()
{
	wchar_t filename[WCHAR_MAX];
	filename[0] = '\0';

	OPENFILENAME ofn;
	memset(&ofn, 0, sizeof(ofn));
	ofn.lStructSize = sizeof(ofn);
	ofn.lpstrFilter = L"iEPGファイル\0*.tvpid;*.tvpi;*.php;*.php3\0全てのファイル\0*.*\0\0";
	ofn.lpstrFile = filename;
	ofn.nMaxFile = WCHAR_MAX;
	ofn.lpstrDefExt = L"";
	ofn.Flags = OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR;

	if( GetOpenFileNameW(&ofn) != TRUE) return;

	EPG epg;
	if(OpenEPGFile(filename, &epg)) SetEPG(&epg);
}


bool CTaskSchedulerHelper2Dlg::OpenSeaIni(void)
{
	FILE	*fp;
	CString pg;
	wchar_t buffer[WCHAR_MAX];
	errno_t err;

	wchar_t szModulePath[256],drv[10],path[256],ext[256];
	wchar_t appname[256],inifilename[256];

	GetModuleFileName(NULL,szModulePath,256);
	_wsplitpath(szModulePath,drv,path,appname,ext);
	_wmakepath(inifilename,drv,path,L"cap_sts_sea",L".ini");
	err = _wfopen_s(&fp, inifilename , L"rt");	//読み込み専用、テキストモード

	if(err) return false;

	for(;;){
		if(fgetws(buffer, WCHAR_MAX, fp) == NULL){	//一行読み込み(S-JIS -> Unicode自動変換)
			// 中身がない
			fclose(fp);
			break;
		}
		if(wcsstr(buffer, L"[VLC_SETTING]") == buffer){
			pg = L"vlc:";
			continue;
		} else if(wcsstr(buffer, L"[FFMPEG_SETTING]") == buffer){
			pg = L"ffmpeg:";
			continue;
		} else if(wcsstr(buffer, L"[") == buffer){
			pg = "";
		} else if(wcsstr(buffer, L";")){
			continue;
		} else if(wcsstr(buffer, L"PATH")){
			continue;
		}

		if(pg != ""){
			wchar_t* arg;
			arg = wcsstr(buffer, L"=");
			if(arg == NULL) continue;
			*arg=NULL;
			CString buf = pg;
			buf+=buffer;
			buf.Trim();
			m_ComboEncode.AddString(buf);
		}
	}		
	
	

	return true;
}

bool CTaskSchedulerHelper2Dlg::OpenEPGFile(const wchar_t * filename, EPG * epg)
{
	FILE	*fp;
	wchar_t buffer[WCHAR_MAX];
	errno_t err;

	err = _wfopen_s(&fp, filename, L"rt");	//読み込み専用、テキストモード
	if(fp == NULL){
		return false;
	}

	memset(epg, '\0', sizeof(EPG));
	epg->start.hour = epg->end.hour = 0xff;

	_wsetlocale(LC_CTYPE, L"Japanese");					//ロケーションセット

	if(fgetws(buffer, WCHAR_MAX, fp) == NULL){	//一行読み込み(S-JIS -> Unicode自動変換)
		// 中身がない
		return false;
	}else
		if(wcsstr(buffer, L"Content-type:") == NULL){
		// 一行目にコンテンツタイプがない
		return false;
	}else if((wcsstr(buffer, L"application/x-tv-program-info") == NULL)&&(wcsstr(buffer, L"application/x-tv-program-digital-info") == NULL)){
		// コンテンツタイプが違う
		return false;
	}	// charsetはShiftJISのみ対応

	int state;
	wchar_t *endp;
	while(true){
		state = 0;
		if(fgetws(buffer, WCHAR_MAX, fp) == NULL) break;
		if(buffer[0] == '\n') state = 14;
		else{
			size_t len = wcslen(buffer);
			buffer[len -1] = '\0';	//改行コードを上書き
		}
///>
#if 1
		if(wcsstr(buffer, L"version: ") == buffer) state = 1;
		if(wcsstr(buffer, L"station: ") == buffer) state = 2;
		if(wcsstr(buffer, L"year: ") == buffer) state = 3;
		if(wcsstr(buffer, L"month: ") == buffer) state = 4;
		if(wcsstr(buffer, L"date: ") == buffer) state = 5;
		if(wcsstr(buffer, L"start: ") == buffer) state = 6;
		if(wcsstr(buffer, L"end: ") == buffer) state = 7;
		if(wcsstr(buffer, L"program-title: ") == buffer) state = 8;
		if(wcsstr(buffer, L"program-subtitle: ") == buffer) state = 9;
		if(wcsstr(buffer, L"performer: ") == buffer) state = 10;
		if(wcsstr(buffer, L"genre: ") == buffer) state = 11;
		if(wcsstr(buffer, L"subgenre: ") == buffer) state = 12;
		if(wcsstr(buffer, L"Extend: ") == buffer) state = 13;
		if(wcsstr(buffer, L"extend: ") == buffer) state = 13;
		//cap_stsTaskViewer連携の拡張.
		if(wcsstr(buffer, L"TASKNAME: ") == buffer) state = 20;
		if(wcsstr(buffer, L"FX2ID: ") == buffer) state = 21;
#else
		if(wcsstr(buffer, L"version: ") != NULL) state = 1;
		if(wcsstr(buffer, L"station: ") != NULL) state = 2;
		if(wcsstr(buffer, L"year: ") != NULL) state = 3;
		if(wcsstr(buffer, L"month: ") != NULL) state = 4;
		if(wcsstr(buffer, L"date: ") != NULL) state = 5;
		if(wcsstr(buffer, L"start: ") != NULL) state = 6;
		if(wcsstr(buffer, L"end: ") != NULL) state = 7;
		if(wcsstr(buffer, L"program-title: ") != NULL) state = 8;
		if(wcsstr(buffer, L"program-subtitle: ") != NULL) state = 9;
		if(wcsstr(buffer, L"performer: ") != NULL) state = 10;
		if(wcsstr(buffer, L"genre: ") != NULL) state = 11;
		if(wcsstr(buffer, L"subgenre: ") != NULL) state = 12;
		if(wcsstr(buffer, L"Extend: ") != NULL) state = 13;
#endif
///<
		switch(state){
			case 1:
				epg->version = (int)wcstol(&buffer[9], &endp, 10);
				break;
			case 2:
				Wcscpy_s(epg->station, EPG_WORD_MAX, &buffer[9]);
				break;
			case 3:
				epg->year = (int)wcstol(&buffer[6], &endp, 10);
				break;
			case 4:
				epg->month = (int)wcstol(&buffer[7], &endp, 10);
				break;
			case 5:
				epg->date = (int)wcstol(&buffer[6], &endp, 10);
				break;
			case 6:
				epg->start.hour = (int)wcstol(&buffer[7], &endp, 10);
				epg->start.minutes = (int)wcstol(&endp[1], &endp, 10);
				break;
			case 7:
				epg->end.hour = (int)wcstol(&buffer[5], &endp, 10);
				epg->end.minutes = (int)wcstol(&endp[1], &endp, 10);
				break;
			case 8:
				Wcscpy_s(epg->program_title, EPG_WORD_MAX, &buffer[15]);
				{///>
					wchar_t c = epg->program_title[0];
					if ( (c >= L'0') && (c <= L'9') ) {
						c += L'０' - L'0';
						epg->program_title[0] = c;
					}
				}///<
				break;
			case 9:
				Wcscpy_s(epg->program_subtitle, EPG_WORD_MAX, &buffer[18]);
				break;
			case 10:
				Wcscpy_s(epg->performer, EPG_WORD_MAX, &buffer[11]);
				break;
			case 11:
				epg->genre = (int)wcstol(&buffer[7], &endp, 10);
				break;
			case 12:
				epg->subgenre = (int)wcstol(&buffer[10], &endp, 10);
				break;
			case 13:
				epg->extend = (int)wcstol(&buffer[8], &endp, 10);
				break;
			case 14:
				while(true){
					if(fgetws(buffer, WCHAR_MAX, fp) == NULL) break;
					Wcscat_s(epg->memo, WCHAR_MAX, buffer);
				}
				break;
///>
			//cap_stsTaskViewer連携の拡張.
			case 20:
			{
				FILE *fp;
				char tmp[512];
				char *srp = getenv("SystemRoot");
				wchar_t *ep = wcsstr(buffer + 10, L".job");
				
				sprintf(tmp,"%s\\Tasks\\",srp);
				wcstombs(tmp + strlen(tmp), buffer + 10, 512);
				///2.1>
				nTaskType = epg->week = 0;
				if ( (fp = fopen(tmp,"rb")) != NULL ) {//直接jobをバイナリ参照するのでVista不可.
					fseek(fp,-16,SEEK_END);
					nTaskType = fgetc(fp);
					fseek(fp,-10,SEEK_END);
					epg->week = fgetc(fp) & 0x07f;
					fclose(fp);
					if ( (nTaskType < 0) || (nTaskType > 2) ) nTaskType = epg->week = 0;
				}
				if ( ep ) *ep = 0;
				Wcscpy_s(epg->task_name, EPG_WORD_MAX, &buffer[10]);
				bForceSet = TRUE;
				nAuto = 2;
				///<
				break;
			}
			case 21:
				strId = &buffer[7];
				break;
///<
			default:
				break;
		}
	}
	fclose(fp);

	tm today;
	time_t time;
	_time64(&time);
	localtime_s(&today, &time);

	if((epg->version != 1)&&(epg->version != 2)) return false;
	if(epg->station[0] == '\0') return false;
	if((epg->start.hour == 0xff)||(epg->end.hour == 0xff)) return false;

	if(epg->year == 0) epg->year = today.tm_year + 1900;
	if(epg->month == 0) epg->month = today.tm_mon +1;
	if(epg->date == 0) epg->date = today.tm_mday;
	if(epg->start.minutes > 59) epg->start.minutes = 59;
	if(epg->start.hour > 23){
		epg->start.hour -= 24;///
		///epg->date += 1;
		///日付を足す{
		struct tm date;
		
		date.tm_isdst = -1;
		date.tm_sec  = 0;
		date.tm_min  = 0;
		date.tm_hour = 12;
		date.tm_mday = epg->date;
		date.tm_mon  = epg->month - 1;
		date.tm_year = epg->year - 1900;
		
		time_t timer = mktime(&date) + (time_t)(60*60*24);//24時間後/
		localtime_s(&date, &timer);
		
		epg->date = date.tm_mday;
		epg->month = date.tm_mon + 1;
		epg->year = date.tm_year + 1900;
		///}
	}
	if(epg->end.minutes > 59) epg->end.minutes = 59;
	if(epg->end.hour > 23) epg->end.hour -= 24;///23

	///>
	epg->end2.minutes = epg->end.minutes + (epg->extend % 60);
	epg->end2.hour = epg->end.hour + (epg->extend / 60) + (epg->end2.minutes / 60);
	epg->end2.hour %= 24;
	epg->end2.minutes %= 60;
	///<

	return true;
}

void CTaskSchedulerHelper2Dlg::LoadChannelFile(void)
{
	FILE	*fp;
	wchar_t buffer[WCHAR_MAX];

	_wsetlocale(LC_CTYPE, L"Japanese");					//ロケーションセット

	channel_number = 0;
	memset(channel, '\0', sizeof(channel));

	wchar_t file[256];
	wchar_t *lastbackslash;
	GetModuleFileNameW(NULL,file,256);
	lastbackslash = wcsrchr(file, '\\');
	Wcscpy_s(lastbackslash, 256 - (lastbackslash - &file[0]), L"\\channel.txt");

	_wfopen_s(&fp, file, L"r+t");	//読み込み専用、テキストモード
	if(fp == NULL){
		return;
	}
	wchar_t *f, *n;
	while(true){
		if(fgetws(buffer, WCHAR_MAX, fp) == NULL) break;
		if(buffer[0] == L'\n') goto SKIP;
		if((buffer[0] == L'/')&&(buffer[1] == L'/')) goto SKIP;

		f = wcschr(&buffer[0], ',');
		Wcsncpy_s(channel[channel_number].name, 32, &buffer[0], f - &buffer[0]);
		f++;
		n = wcschr(f, ',');
		Wcsncpy_s(channel[channel_number].command, 10, f, n - f);
		n++;
		Wcscpy_s(channel[channel_number].IdentificationWord, 128, n);
		channel_number++;

		SKIP:
		;
	}
	fclose(fp);
}

void CTaskSchedulerHelper2Dlg::SetEPG(const EPG * epg)
{
		CTime sdt(epg->year, epg->month, epg->date, epg->start.hour, epg->start.minutes, 0);
		ctrlCal.SetCurSel(sdt);
		OnMcnSelectMonthcalendar(NULL,NULL);
		ctrlDateTime1.SetTime(&sdt);
		CTime edt0(epg->year, epg->month, epg->date, epg->end.hour , epg->end.minutes , 0);
		CTime edt1(epg->year, epg->month, epg->date, epg->end2.hour, epg->end2.minutes, 0);
		endt[0] = edt0;
		endt[1] = edt1;
		ctrlDateTime2.SetTime(&(endt[(int)bExtend]));
		
		s_title.Format(_T("%s"), epg->program_title);
		if(epg->program_subtitle[0] == '\0'){
			s_subtitle = s_title;
		}else{
			s_subtitle.Format(_T("%s-%s"), epg->program_title, epg->program_subtitle);
		}
		strFilename = (bSubtitle ? s_subtitle : s_title);
		//strTaskName = epg->program_title;
		strTaskName = epg->task_name[0] ? epg->task_name : epg->program_title;//変更. 
		if(bParentheses){
			DeleteParentheses(&strFilename);
			DeleteParentheses(&strTaskName);
		}

		if ( epg->week ) {///2.1
			int week = epg->week;
			
			if ( (epg->start.hour==0) && (epg->start.minutes==0) ) {
				//00:00ではローテイトしてる.
				week <<= 1;
				if ( (week & 0x080) != 0 ) week++;
			}
			for ( int n = 0; n < 7; n++ ) {
				bWeek[n] = ((week & 1) != 0);
				week >>= 1;
			}
		}

		int i;
		for(i = 0;i < channel_number; i++){
			if(wcsstr(channel[i].IdentificationWord, epg->station) != NULL) break;
		}
		if(i == channel_number){
			strChannel = "";
			ctrlChannelList.SetCurSel(-1);
			AfxMessageBox(L"チャンネル設定ファイルに無いチャンネルです。\r\n手動でチャンネルコマンドを入力してください。");
		}else{
			strChannel = channel[i].command;
			ctrlChannelList.SetCurSel(i);
		}

		UpdateData(false);
		MakeCommandline();
}

void CTaskSchedulerHelper2Dlg::OnBnClickedExtendCheck()
{
	UpdateData(TRUE);
	MakeCommandline();
	ctrlDateTime2.SetTime(&(endt[(int)bExtend]));
	UpdateData(false);
	MakeCommandline();
}

void CTaskSchedulerHelper2Dlg::OnDeltaposIdSpin(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMUPDOWN pNMUpDown = reinterpret_cast<LPNMUPDOWN>(pNMHDR);
	int fx2id = -1;

	UpdateData(TRUE);
	MakeCommandline();

	if ( strId[0] != 0 ) fx2id = (int)wcstod(strId, NULL);
	fx2id += pNMUpDown->iDelta;
	if ( fx2id < 0 ) fx2id = 0;
	if ( fx2id > 9 ) fx2id = 9;
	strId.Format(_T("%d"), fx2id);

	UpdateData(false);
	MakeCommandline();

	*pResult = 0;
}

void CTaskSchedulerHelper2Dlg::OnLbnSelchangeChannelList()
{
	UpdateData(TRUE);
	int num = ctrlChannelList.GetCurSel();
	strChannel = channel[num].command;

	MakeCommandline();
}

void CTaskSchedulerHelper2Dlg::OnTcnSelchangingOptionTab(NMHDR *pNMHDR, LRESULT *pResult)
{
	UpdateData(TRUE);
	GetOptions();
	*pResult = 0;
}

void CTaskSchedulerHelper2Dlg::OnTcnSelchangeOptionTab(NMHDR *pNMHDR, LRESULT *pResult)
{
	int num = ctrlOptTab.GetCurSel();
	SetOptions(num);
	UpdateData(FALSE);
	MakeCommandline();
	*pResult = 0;
}

void CTaskSchedulerHelper2Dlg::OnBnClickedAddOptionButton()
{
	if(opt_number >= (OPTION_MAX -1)) return;

	CNameInputDlg dlg;
	if(dlg.DoModal() == IDOK){
		int num = ctrlOptTab.GetCurSel();
		memcpy(&opt[opt_number], &opt[num], sizeof(OPTION));
		wcscpy_s(opt[opt_number].Title, 50, dlg.strOptionTitle);

		TC_ITEM myTCitem;
		myTCitem.mask = TCIF_TEXT;
		myTCitem.pszText = opt[opt_number].Title;
		ctrlOptTab.InsertItem(opt_number, &myTCitem);

		ctrlOptTab.SetCurSel(opt_number);
		opt_number++;
	}
}

void CTaskSchedulerHelper2Dlg::OnBnClickedDelOptionButton()
{
	int num = ctrlOptTab.GetCurSel();
	if((num < 0)||(num >= opt_number)||(opt_number <= 1)) return;

	for(int i = num; i < (opt_number - 1); i++){
		memcpy(&opt[i], &opt[i+1], sizeof(OPTION));
	}
	SetOptions(0);
	ctrlOptTab.DeleteItem(num);
	ctrlOptTab.SetCurSel(0);
	opt_number--;
	
	UpdateData(FALSE);
	MakeCommandline();
}

void CTaskSchedulerHelper2Dlg::DeleteParentheses(CString *str)
{
	size_t len = str->GetLength() +1;
	if(len < 1) return;

	wchar_t *src, *temp, *p;
	src = new wchar_t [len];
	temp = new wchar_t [len];

	wcscpy_s(src, len, str->GetString());

	p = (wchar_t *)wcschr(src, L'[');
	if(p != NULL){
		wcsncpy_s(temp, len, src, p - src);
		p = (wchar_t *)wcsrchr(src, L']');
		if(p != NULL){
			wcscat_s(temp, len, p + 1);
			str->SetString(temp);
		}
	}
	delete[] temp;
	delete[] src;

	return;
}

void CTaskSchedulerHelper2Dlg::OnBnClickedTaskviewerButton()
{
	wchar_t pn[256];
	CString cmd;

	GetModuleFileName(NULL, pn, 256-1);
	wcsrchr(pn, L'\\')[1] = 0;
	cmd = pn;
	cmd += "cap_stsTaskViewer.exe";
	ShellExecute(NULL, L"open", cmd, NULL, NULL, SW_SHOW); 

}

void CTaskSchedulerHelper2Dlg::OnBnClickedSubtitleCheck()
{
	if(s_subtitle == "") return;

	UpdateData(TRUE);
	MakeCommandline();
	strFilename = (bSubtitle ? s_subtitle : s_title);
	if(bParentheses) DeleteParentheses(&strFilename);
	UpdateData(false);
	MakeCommandline();
}

void CTaskSchedulerHelper2Dlg::OnBnClickedParenthesesCheck()
{
	UpdateData(TRUE);
	MakeCommandline();
	if(bParentheses){
		DeleteParentheses(&strFilename);
		DeleteParentheses(&strTaskName);
	}
	UpdateData(false);
	MakeCommandline();
}

void CTaskSchedulerHelper2Dlg::OnMcnSelectMonthcalendar(NMHDR *pNMHDR, LRESULT *pResult)///2.1
{
	CTime SetTimeTmp;
	LPNMSELCHANGE pSelChange = reinterpret_cast<LPNMSELCHANGE>(pNMHDR);
	
	if ( pSelChange ) {
		UpdateData(TRUE);
		MakeCommandline();
	}
	else {
		for ( int n = 0; n < 7; n++ ) bWeek[n] = FALSE;
	}
	ctrlCal.GetCurSel(SetTimeTmp);
	bWeek[selWeek = (SetTimeTmp.GetDayOfWeek() - 1)] = TRUE;
	
	if ( pSelChange ) {
		UpdateData(false);
		MakeCommandline();
	}
	
	if ( pResult ) *pResult = 0;
}

void CTaskSchedulerHelper2Dlg::LoadIniFile(void)
{
	wchar_t *lastbackslash;
	wchar_t ini_pathname[256];
	GetModuleFileNameW(NULL, ini_pathname, 256);
	lastbackslash = wcsrchr(ini_pathname, '\\');
	Wcscpy_s(lastbackslash, 256 - (lastbackslash - &ini_pathname[0]), L"\\TaskSchedulerHelper_setting.ini");

	wchar_t index[10], temp[256];
	memset(opt, 0, sizeof(opt));
	bAutoClose = GetPrivateProfileIntW(L"system", L"autoclose", 0, ini_pathname);
	int cursor = GetPrivateProfileIntW(L"system", L"cursor", 0, ini_pathname);
	opt_number = GetPrivateProfileIntW(L"system", L"option_number", 1, ini_pathname);
	if(opt_number < 1) opt_number = 1;
	if(opt_number >= OPTION_MAX) opt_number = OPTION_MAX -1;

	GetPrivateProfileStringW(L"general", L"channel", L"001", temp, 10, ini_pathname);
	strChannel = temp;
	bSubtitle = GetPrivateProfileIntW(L"general", L"subtitle", 1, ini_pathname);
	bExtend = GetPrivateProfileIntW(L"general", L"extend", 0, ini_pathname);
	bParentheses = GetPrivateProfileIntW(L"general", L"Parentheses", 0, ini_pathname);

	TC_ITEM myTCitem;
	myTCitem.mask = TCIF_TEXT;
	for(int i = 0; i < opt_number; i++){
		swprintf_s(index, 10, L"cap_sts_%u", i);
		if(i == 0) index[7] = '\0';

		GetPrivateProfileStringW(index, L"title",		NULL,			opt[i].Title,		50,		ini_pathname);
		GetPrivateProfileStringW(index, L"cap_sts_path",L"cap_sts.exe",	opt[i].Capsts,		256,	ini_pathname);
		GetPrivateProfileStringW(index, L"folder",		L"C:",			opt[i].Foldername,	256,	ini_pathname);
		GetPrivateProfileStringW(index, L"vlc_parm",	L"",			opt[i].VlcParam,	30,		ini_pathname);
		GetPrivateProfileStringW(index, L"id",			L"0",			opt[i].Id,			10,		ini_pathname);
		GetPrivateProfileStringW(index, L"fileext",		L".ts",			opt[i].FileExt,		10,		ini_pathname);

		opt[i].PowerOn	= GetPrivateProfileIntW(index, L"power_on",		0, ini_pathname);
		opt[i].PowerOff	= GetPrivateProfileIntW(index, L"power_off",	0, ini_pathname);
		opt[i].Bcs		= GetPrivateProfileIntW(index, L"bcs",			1, ini_pathname);
		opt[i].B25		= GetPrivateProfileIntW(index, L"b25",			0, ini_pathname);
		opt[i].Vlc		= GetPrivateProfileIntW(index, L"vlc",			0, ini_pathname);
		opt[i].Sel		= GetPrivateProfileIntW(index, L"sel",			0, ini_pathname);
		opt[i].Sus		= GetPrivateProfileIntW(index, L"sus",			0, ini_pathname);
		opt[i].Rmc		= GetPrivateProfileIntW(index, L"rmc",			0, ini_pathname);

		if((i == 0)&&(opt[i].Title[0] == '\0')) Wcscpy_s(opt[i].Title, 50, L"default");
		myTCitem.pszText = opt[i].Title;
		ctrlOptTab.InsertItem(i, &myTCitem);
	}
	if((cursor < 0)||(cursor >= opt_number)) cursor = 0;
	ctrlOptTab.SetCurSel(cursor);

	GetPrivateProfileStringW(L"task", L"account",	NULL, temp, 256, ini_pathname); 
	strAccount = temp;
	GetPrivateProfileStringW(L"task", L"pass",		NULL, temp, 256, ini_pathname);
	strPass1 = strPass2 = temp;
	bDelTask = GetPrivateProfileIntW(L"task", L"del_task", 0, ini_pathname);
	bResume	 = GetPrivateProfileIntW(L"task", L"resume", 0, ini_pathname);
	//bForceSet = GetPrivateProfileIntW(L"system", L"forceset", 1, ini_pathname);
}

void CTaskSchedulerHelper2Dlg::SaveIniFile(void)
{
	wchar_t *lastbackslash;
	wchar_t ini_pathname[256];
	GetModuleFileNameW(NULL, ini_pathname, 256);
	lastbackslash = wcsrchr(ini_pathname, '\\');
	Wcscpy_s(lastbackslash, 256 - (lastbackslash - &ini_pathname[0]), L"\\TaskSchedulerHelper_setting.ini");

	CString temp;
	temp.Format(_T("%u"), bAutoClose);
	WritePrivateProfileStringW(L"system", L"autoclose", temp, ini_pathname);
	temp.Format(_T("%u"), ctrlOptTab.GetCurSel());
	WritePrivateProfileStringW(L"system", L"cursor", temp, ini_pathname);
	temp.Format(_T("%u"), opt_number);
	WritePrivateProfileStringW(L"system", L"option_number", temp, ini_pathname);

	WritePrivateProfileStringW(L"general", L"channel", strChannel, ini_pathname);
	temp.Format(_T("%u"), bSubtitle);
	WritePrivateProfileStringW(L"general", L"subtitle", temp, ini_pathname);
	temp.Format(_T("%u"), bExtend);
	WritePrivateProfileStringW(L"general", L"extend", temp, ini_pathname);
	temp.Format(_T("%u"), bParentheses);
	WritePrivateProfileStringW(L"general", L"Parentheses", temp, ini_pathname);

	wchar_t index[10];
	for(int i = 0; i < opt_number; i++){
		swprintf_s(index, 10, L"cap_sts_%u", i);
		if(i == 0) index[7] = '\0';

		WritePrivateProfileStringW(index, L"title",			opt[i].Title,		ini_pathname);
		WritePrivateProfileStringW(index, L"cap_sts_path",	opt[i].Capsts,		ini_pathname);
		WritePrivateProfileStringW(index, L"folder",		opt[i].Foldername,	ini_pathname);
		WritePrivateProfileStringW(index, L"vlc_parm",		opt[i].VlcParam,	ini_pathname);
		WritePrivateProfileStringW(index, L"id",			opt[i].Id,			ini_pathname);
		WritePrivateProfileStringW(index, L"fileext",		opt[i].FileExt,		ini_pathname);

		temp.Format(_T("%u"), opt[i].PowerOn);
		WritePrivateProfileStringW(index, L"power_on", temp, ini_pathname);
		temp.Format(_T("%u"), opt[i].PowerOff);
		WritePrivateProfileStringW(index, L"power_off", temp, ini_pathname);
		temp.Format(_T("%u"), opt[i].Bcs);
		WritePrivateProfileStringW(index, L"bcs", temp, ini_pathname);
		temp.Format(_T("%u"), opt[i].B25);
		WritePrivateProfileStringW(index, L"b25", temp, ini_pathname);
		temp.Format(_T("%u"), opt[i].Vlc);
		WritePrivateProfileStringW(index, L"vlc", temp, ini_pathname);
		temp.Format(_T("%u"), opt[i].Sel);
		WritePrivateProfileStringW(index, L"sel", temp, ini_pathname);
		temp.Format(_T("%u"), opt[i].Sus);
		WritePrivateProfileStringW(index, L"sus", temp, ini_pathname);
		temp.Format(_T("%u"), opt[i].Rmc);
		WritePrivateProfileStringW(index, L"rmc", temp, ini_pathname);
	}
	WritePrivateProfileStringW(L"task", L"account", strAccount, ini_pathname);
	WritePrivateProfileStringW(L"task", L"pass", strPass1, ini_pathname);
	temp.Format(_T("%u"), bDelTask);
	WritePrivateProfileStringW(L"task", L"del_task", temp, ini_pathname);
	temp.Format(_T("%u"), bResume);
	WritePrivateProfileStringW(L"task", L"resume", temp, ini_pathname);
	//temp.Format(_T("%u"), bForceSet);///
	//WritePrivateProfileStringW(L"system", L"forceset", temp, ini_pathname);///
}

void CTaskSchedulerHelper2Dlg::OnBnClickedWeek()
{
	UpdateData(TRUE);
	if ( selWeek >= 0 ) bWeek[selWeek] = TRUE;
	UpdateData(FALSE);
}

void CTaskSchedulerHelper2Dlg::OnCbnCloseupComboEncode()
{
	// TODO: ここにコントロール通知ハンドラ コードを追加します。
	ChangeOptions();
	OnBnClickedExtendCheck();
}
